Compare commits
68 Commits
feature/re
...
tenant/des
| Author | SHA1 | Date | |
|---|---|---|---|
| 0defe75adb | |||
| 34afb5142d | |||
| 8eba15155e | |||
| 85c31579e2 | |||
| 159ec36cb2 | |||
| 32b1eb5639 | |||
| 0f9d3e79d4 | |||
| b97753f825 | |||
| f1b724ed63 | |||
| 571cae0f98 | |||
| 30b8527c9a | |||
| 0e5f6dceb0 | |||
| cd0a6e9b5e | |||
| 1bbb3d0914 | |||
| e4157a4005 | |||
| c9f8a1c4a6 | |||
| 308af52ad5 | |||
| ae6728998d | |||
| f1b829264f | |||
| fccb7676bf | |||
| 3adc04b68d | |||
| 12e2870d40 | |||
| 0b53253461 | |||
| 6cc0fcd9c0 | |||
| dc6668df72 | |||
| f428a88ba8 | |||
| e21c5e9e9f | |||
| f7a8b42892 | |||
| 9f8e42c30b | |||
| d45199a0ef | |||
| c1da31711f | |||
| cf61611d76 | |||
| 2c4d22f0b9 | |||
| caa1fddcc1 | |||
| 5f0c99c395 | |||
| 832fad19bc | |||
| 28ed5d71b2 | |||
| 23a5ac32cc | |||
| 1b19d36e26 | |||
| 86533b9ab4 | |||
| 369cfb0a40 | |||
| 7b0c9831f1 | |||
| ede2173a5a | |||
| 5d760bfd80 | |||
| e3599a48e4 | |||
| 5d629e27b1 | |||
| 563e4634d1 | |||
| c75787a59c | |||
| f6f3a997f7 | |||
| 019c9df23b | |||
| 9ea85b7924 | |||
| 0769bb8683 | |||
| c645feba80 | |||
| 56f602d876 | |||
| d6bab24e1d | |||
| dd828d9a4e | |||
| 7c2a098696 | |||
| 1977df6765 | |||
| c6ac974459 | |||
| 8d88e1bb13 | |||
| 78970573a8 | |||
| f289e9e2e4 | |||
| 2487546a75 | |||
| cc884e3cc0 | |||
| ffb586c348 | |||
| ec18aaf0c5 | |||
| 941cb5c73c | |||
| 934bd07105 |
13
angular.json
13
angular.json
@@ -64,7 +64,13 @@
|
||||
"local": {
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true
|
||||
"sourceMap": true,
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "src/environments/environment.ts",
|
||||
"with": "src/environments/environment.local.ts"
|
||||
}
|
||||
]
|
||||
},
|
||||
"homo": {
|
||||
"fileReplacements": [
|
||||
@@ -79,6 +85,9 @@
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular/build:dev-server",
|
||||
"options": {
|
||||
"port": 4300
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"buildTarget": "shopit-front:build:production"
|
||||
@@ -93,7 +102,7 @@
|
||||
"buildTarget": "shopit-front:build:homo"
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "development"
|
||||
"defaultConfiguration": "local"
|
||||
},
|
||||
"test": {
|
||||
"builder": "@angular/build:unit-test"
|
||||
|
||||
BIN
public/images/ticket-selector-entrada-pasarela.png
Normal file
BIN
public/images/ticket-selector-entrada-pasarela.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 333 KiB |
@@ -17,7 +17,7 @@
|
||||
.tenant-status__card {
|
||||
width: min(100%, 34rem);
|
||||
padding: 2rem;
|
||||
border: 1px solid rgba(32, 32, 32, 0.1);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 1.5rem;
|
||||
background-color: rgba(255, 255, 255, 0.92);
|
||||
box-shadow: 0 1.25rem 3rem rgba(0, 0, 0, 0.1);
|
||||
@@ -55,7 +55,7 @@
|
||||
.tenant-status__spinner {
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
border: 0.25rem solid rgba(32, 32, 32, 0.08);
|
||||
border: 0.25rem solid var(--border-color);
|
||||
border-top-color: var(--tenant-primary);
|
||||
border-radius: 999px;
|
||||
animation: tenant-status-spin 0.8s linear infinite;
|
||||
|
||||
@@ -17,6 +17,8 @@ const tenant: Tenant = {
|
||||
codigo: 'test',
|
||||
nombre: 'Test Tenant',
|
||||
dominio: 'localhost',
|
||||
site_title: 'Test Store',
|
||||
favicon: 'https://example.com/favicon.png',
|
||||
primary_color: '#6376F3',
|
||||
secondary_color: '#A0A0A0',
|
||||
danger_color: '#FF8888',
|
||||
@@ -90,6 +92,9 @@ describe('App', () => {
|
||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-danger-rgb')).toBe(
|
||||
'255, 136, 136'
|
||||
);
|
||||
expect(document.title).toBe(tenant.site_title);
|
||||
expect(document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'))
|
||||
.toBe(tenant.favicon);
|
||||
});
|
||||
|
||||
it('renders the tenant not found screen when the tenant is missing', async () => {
|
||||
@@ -108,5 +113,8 @@ describe('App', () => {
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.nativeElement.textContent).toContain('No encontramos una tienda para este dominio');
|
||||
expect(document.title).toBe('ShopitFront');
|
||||
expect(document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'))
|
||||
.toBe('favicon.ico');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Component, computed, inject } from '@angular/core';
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { Component, computed, effect, inject } from '@angular/core';
|
||||
import { Title } from '@angular/platform-browser';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
|
||||
import { TenantService } from './core/services/tenant.service';
|
||||
@@ -57,6 +59,28 @@ function hexToRgb(hex: string): string {
|
||||
})
|
||||
export class App {
|
||||
private readonly tenantService = inject(TenantService);
|
||||
private readonly document = inject(DOCUMENT);
|
||||
private readonly title = inject(Title);
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const tenant = this.tenantService.tenant();
|
||||
const siteTitle = tenant?.site_title?.trim() || 'ShopitFront';
|
||||
const faviconHref = tenant?.favicon || 'favicon.ico';
|
||||
|
||||
this.title.setTitle(siteTitle);
|
||||
|
||||
let favicon = this.document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]');
|
||||
|
||||
if (!favicon) {
|
||||
favicon = this.document.createElement('link');
|
||||
favicon.setAttribute('rel', 'icon');
|
||||
this.document.head.appendChild(favicon);
|
||||
}
|
||||
|
||||
favicon.setAttribute('href', faviconHref);
|
||||
});
|
||||
}
|
||||
|
||||
protected readonly status = this.tenantService.status;
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
<footer class="store-layout__footer mt-auto text-light">
|
||||
<footer
|
||||
class="store-layout__footer mt-auto text-light"
|
||||
[style.background-image]="backgroundImageUrl ? 'url(' + backgroundImageUrl + ')' : null"
|
||||
>
|
||||
<div class="container-xl px-3 px-md-4 py-4 py-md-5 store-layout__footer-content">
|
||||
<div class="row g-4 store-layout__footer-grid">
|
||||
<div class="col-12 store-layout__brand-column">
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
.store-layout__footer {
|
||||
background-color: var(--tenant-footer-bg);
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
background-size: cover;
|
||||
}
|
||||
|
||||
.store-layout__mobile-divider {
|
||||
@@ -7,21 +10,21 @@
|
||||
}
|
||||
|
||||
.store-layout__brand-slot {
|
||||
width: min(100%, 12rem);
|
||||
width: min(100%, 230px);
|
||||
min-width: 10rem;
|
||||
}
|
||||
|
||||
.store-layout__brand-logo-shell {
|
||||
position: relative;
|
||||
width: min(100%, 12rem);
|
||||
height: 2.75rem;
|
||||
width: min(100%, 230px);
|
||||
height: 65px;
|
||||
}
|
||||
|
||||
.store-layout__brand-logo {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
max-height: 2.75rem;
|
||||
max-height: 65px;
|
||||
object-fit: contain;
|
||||
object-position: left center;
|
||||
}
|
||||
@@ -46,7 +49,7 @@
|
||||
place-items: center;
|
||||
width: 2.75rem;
|
||||
height: 2.75rem;
|
||||
border: 1px dashed rgba(255, 255, 255, 0.35);
|
||||
border: 1px dashed var(--border-color);
|
||||
border-radius: 999px;
|
||||
font-size: 1.05rem;
|
||||
font-weight: 700;
|
||||
@@ -67,7 +70,7 @@
|
||||
|
||||
.store-layout__footer-link {
|
||||
width: fit-content;
|
||||
color: rgba(255, 255, 255, 0.72);
|
||||
color: #ffffff;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover,
|
||||
@@ -98,6 +101,7 @@
|
||||
@media (max-width: 767.98px) {
|
||||
.store-layout__footer-content {
|
||||
padding: 1.45rem 2.5rem 1.8rem !important;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.store-layout__footer-grid {
|
||||
@@ -117,7 +121,6 @@
|
||||
order: 1;
|
||||
width: auto;
|
||||
padding-bottom: 1.65rem;
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.25;
|
||||
|
||||
&:nth-of-type(even) {
|
||||
@@ -133,8 +136,8 @@
|
||||
display: block;
|
||||
order: 2;
|
||||
grid-column: 1 / -1;
|
||||
width: 100vw;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.3);
|
||||
width: 100%;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.store-layout__brand-column,
|
||||
@@ -145,21 +148,21 @@
|
||||
}
|
||||
|
||||
.store-layout__brand-slot {
|
||||
width: min(100%, 7.75rem);
|
||||
width: min(100%, 150px);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.store-layout__brand-logo {
|
||||
max-height: 2.5rem;
|
||||
max-height: 55px;
|
||||
}
|
||||
|
||||
.store-layout__brand-logo-shell {
|
||||
width: min(100%, 7.75rem);
|
||||
height: 2.5rem;
|
||||
width: min(100%, 150px);
|
||||
height: 55px;
|
||||
}
|
||||
|
||||
.store-layout__brand-text {
|
||||
font-size: 1.45rem;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.store-layout__social-column {
|
||||
@@ -183,11 +186,10 @@
|
||||
.store-layout__contact-details {
|
||||
justify-items: center;
|
||||
gap: 0.4rem !important;
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
.store-layout__copyright {
|
||||
font-size: 0.6rem;
|
||||
font-size: 11px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ export class StoreFooterComponent {
|
||||
@Input({ required: true }) footerSections: StoreFooterSection[] = [];
|
||||
@Input({ required: true }) socialMedia: SocialMedia[] = [];
|
||||
@Input() logoUrl: string | null = null;
|
||||
@Input() backgroundImageUrl: string | null = null;
|
||||
@Input() storeName: string | null = null;
|
||||
readonly logoutClick = output<void>();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
<header class="store-layout__header">
|
||||
<header
|
||||
class="store-layout__header"
|
||||
[style.background-image]="backgroundImageUrl() ? 'url(' + backgroundImageUrl() + ')' : null"
|
||||
>
|
||||
<div class="store-layout__header-main">
|
||||
<div class="container-xl px-3 px-md-4 py-3 py-lg-4">
|
||||
<div class="row align-items-center gy-3 gy-md-0">
|
||||
@@ -19,46 +22,50 @@
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="col-12 px-0 d-md-none order-3">
|
||||
<hr class="store-layout__mobile-separator">
|
||||
</div>
|
||||
|
||||
<div class="col-12 col-md order-4 order-md-2">
|
||||
<div class="store-layout__search-wrapper ms-md-auto">
|
||||
<div class="input-group store-layout__search" role="search">
|
||||
<label class="visually-hidden" for="store-search-input">Buscar productos</label>
|
||||
<input
|
||||
id="store-search-input"
|
||||
type="search"
|
||||
class="form-control store-layout__search-input border-end-0 rounded-start"
|
||||
placeholder="Buscar productos"
|
||||
autocomplete="off"
|
||||
[attr.aria-describedby]="showSearchError() ? 'store-search-error' : null"
|
||||
[attr.aria-invalid]="showSearchError()"
|
||||
[minlength]="minSearchLength"
|
||||
[formControl]="searchControl"
|
||||
(input)="clearSearchError()"
|
||||
(keydown.enter)="submitSearch($event)"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="btn store-layout__search-button border-start-0 rounded-end px-3"
|
||||
aria-label="Buscar"
|
||||
(click)="submitSearch()"
|
||||
>
|
||||
<i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (showSearchError()) {
|
||||
<p id="store-search-error" class="store-layout__search-error mb-0" role="alert">
|
||||
Ingresá al menos {{ minSearchLength }} caracteres para buscar.
|
||||
</p>
|
||||
}
|
||||
@if (displaySeachBar()) {
|
||||
<div class="col-12 px-0 d-md-none order-3">
|
||||
<hr class="store-layout__mobile-separator" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="store-layout__actions-column col-auto col-md-auto order-2 order-md-3 ms-auto d-flex flex-row align-items-center justify-content-end gap-2 gap-md-3">
|
||||
<div class="col-12 col-md order-4 order-md-2">
|
||||
<div class="store-layout__search-wrapper ms-md-auto">
|
||||
<div class="input-group store-layout__search" role="search">
|
||||
<label class="visually-hidden" for="store-search-input">Buscar productos</label>
|
||||
<input
|
||||
id="store-search-input"
|
||||
type="search"
|
||||
class="form-control store-layout__search-input border-end-0 rounded-start"
|
||||
placeholder="Buscar productos"
|
||||
autocomplete="off"
|
||||
[attr.aria-describedby]="showSearchError() ? 'store-search-error' : null"
|
||||
[attr.aria-invalid]="showSearchError()"
|
||||
[minlength]="minSearchLength"
|
||||
[formControl]="searchControl"
|
||||
(input)="clearSearchError()"
|
||||
(keydown.enter)="submitSearch($event)"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="btn store-layout__search-button border-start-0 rounded-end px-3"
|
||||
aria-label="Buscar"
|
||||
(click)="submitSearch()"
|
||||
>
|
||||
<i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (showSearchError()) {
|
||||
<p id="store-search-error" class="store-layout__search-error mb-0" role="alert">
|
||||
Ingresá al menos {{ minSearchLength }} caracteres para buscar.
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div
|
||||
class="store-layout__actions-column col-auto col-md-auto order-2 order-md-3 ms-auto d-flex flex-row align-items-center justify-content-end gap-2 gap-md-3"
|
||||
>
|
||||
@if (ticketsMenu(); as menu) {
|
||||
<app-button
|
||||
variant="primary"
|
||||
@@ -70,12 +77,14 @@
|
||||
</app-button>
|
||||
}
|
||||
|
||||
<app-cart-icon
|
||||
[quantity]="cartQuantity()"
|
||||
ariaLabel="Carrito de compras"
|
||||
title="Carrito"
|
||||
(click)="cartClick.emit()"
|
||||
/>
|
||||
@if (displayCart()) {
|
||||
<app-cart-icon
|
||||
[quantity]="cartQuantity()"
|
||||
ariaLabel="Carrito de compras"
|
||||
title="Carrito"
|
||||
(click)="cartClick.emit()"
|
||||
/>
|
||||
}
|
||||
|
||||
<div class="store-layout__user-menu d-none d-md-inline-flex position-relative">
|
||||
<app-icon-button
|
||||
@@ -108,24 +117,29 @@
|
||||
/>
|
||||
|
||||
@if (isMobileMenuOpen()) {
|
||||
<div id="store-mobile-menu" class="position-absolute end-0 bg-white rounded shadow mt-2 py-2 store-layout__mobile-dropdown-menu">
|
||||
<a
|
||||
class="dropdown-item d-flex align-items-center gap-2 px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
||||
<div
|
||||
id="store-mobile-menu"
|
||||
class="position-absolute end-0 bg-white rounded shadow mt-2 py-2 store-layout__mobile-dropdown-menu"
|
||||
>
|
||||
<a
|
||||
class="dropdown-item d-flex align-items-center gap-2 px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
||||
(click)="onMobileAccountClick()"
|
||||
>
|
||||
<i class="fa-regular fa-circle-user fa-lg"></i>
|
||||
<span class="fw-medium">Mi cuenta</span>
|
||||
</a>
|
||||
|
||||
<hr class="my-1 border-secondary opacity-25">
|
||||
@if (displayCategories()) {
|
||||
<hr class="my-1 border-secondary opacity-25" />
|
||||
|
||||
@for (category of categories(); track category.id) {
|
||||
<a
|
||||
class="dropdown-item px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
||||
(click)="onCategorySelect(category)"
|
||||
>
|
||||
<span class="fw-medium">{{ category.nombre }}</span>
|
||||
</a>
|
||||
@for (category of categories(); track category.id) {
|
||||
<a
|
||||
class="dropdown-item px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
||||
(click)="onCategorySelect(category)"
|
||||
>
|
||||
<span class="fw-medium">{{ category.nombre }}</span>
|
||||
</a>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@@ -135,28 +149,30 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="store-layout__categories d-none d-md-block">
|
||||
<div class="container-xl px-3 px-md-4">
|
||||
<div class="store-layout__category-menu">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-link d-inline-flex align-items-center gap-2 px-0 py-2 text-uppercase fw-bold text-decoration-none store-layout__category-trigger"
|
||||
aria-label="Categorias"
|
||||
aria-controls="store-category-dropdown"
|
||||
[attr.aria-expanded]="isCategoryDropdownOpen()"
|
||||
(click)="toggleCategoryDropdown()"
|
||||
>
|
||||
<span>Categorias</span>
|
||||
<i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
|
||||
</button>
|
||||
@if (displayCategories()) {
|
||||
<div class="store-layout__categories d-none d-md-block">
|
||||
<div class="container-xl px-3 px-md-4">
|
||||
<div class="store-layout__category-menu">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-link d-inline-flex align-items-center gap-2 px-0 py-3 text-uppercase fw-bold text-decoration-none store-layout__category-trigger"
|
||||
aria-label="Categorias"
|
||||
aria-controls="store-category-dropdown"
|
||||
[attr.aria-expanded]="isCategoryDropdownOpen()"
|
||||
(click)="toggleCategoryDropdown()"
|
||||
>
|
||||
<span>Categorias</span>
|
||||
<i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
|
||||
</button>
|
||||
|
||||
<app-category-dropdown
|
||||
id="store-category-dropdown"
|
||||
[categories]="categories()"
|
||||
[open]="isCategoryDropdownOpen()"
|
||||
(categorySelect)="onCategorySelect($event)"
|
||||
/>
|
||||
<app-category-dropdown
|
||||
id="store-category-dropdown"
|
||||
[categories]="categories()"
|
||||
[open]="isCategoryDropdownOpen()"
|
||||
(categorySelect)="onCategorySelect($event)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</header>
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
.store-layout__header {
|
||||
color: #ffffff;
|
||||
background-color: var(--tenant-header-bg);
|
||||
box-shadow: inset 0 -1px 0 rgba(255, 255, 255, 0.08);
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
background-size: cover;
|
||||
}
|
||||
|
||||
.store-layout__header-main {
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.store-layout__brand-slot {
|
||||
@@ -77,7 +79,7 @@
|
||||
|
||||
.store-layout__search-input {
|
||||
color: #666666;
|
||||
border-color: #cccccc;
|
||||
border-color: var(--border-color);
|
||||
background-color: rgba(255, 255, 255, 0.96);
|
||||
}
|
||||
|
||||
@@ -86,21 +88,21 @@
|
||||
}
|
||||
|
||||
.store-layout__search-input:focus {
|
||||
border-color: #cccccc;
|
||||
border-color: var(--border-color);
|
||||
box-shadow: none;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.store-layout__search-button {
|
||||
color: #a0a0a0;
|
||||
border-color: #cccccc;
|
||||
border-color: var(--border-color);
|
||||
background-color: rgba(255, 255, 255, 0.96);
|
||||
}
|
||||
|
||||
.store-layout__search-button:hover,
|
||||
.store-layout__search-button:focus-visible {
|
||||
color: #8a8a8a;
|
||||
border-color: #cccccc;
|
||||
border-color: var(--border-color);
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
@@ -158,8 +160,21 @@
|
||||
max-width: 150px;
|
||||
}
|
||||
|
||||
.store-layout__actions-column {
|
||||
flex: 1 1 auto;
|
||||
width: auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
::ng-deep .store-layout__tickets-btn-host {
|
||||
flex: 1 1 0;
|
||||
width: auto;
|
||||
min-width: 0;
|
||||
max-width: 50vw;
|
||||
}
|
||||
|
||||
.store-layout__mobile-separator {
|
||||
border-color: #DDDDDD;
|
||||
border-color: var(--border-color);
|
||||
opacity: 1;
|
||||
margin: 0 -1rem;
|
||||
}
|
||||
@@ -180,8 +195,9 @@
|
||||
}
|
||||
|
||||
.store-layout__actions-column {
|
||||
flex: 0 0 auto;
|
||||
flex: 1 1 auto;
|
||||
width: auto;
|
||||
min-width: 0;
|
||||
margin-left: 0 !important;
|
||||
padding-left: 0.25rem;
|
||||
gap: 0.25rem !important;
|
||||
|
||||
@@ -29,12 +29,16 @@ export class StoreHeaderComponent {
|
||||
private readonly router = inject(Router);
|
||||
|
||||
readonly logoUrl = input<string | null>(null);
|
||||
readonly backgroundImageUrl = input<string | null>(null);
|
||||
readonly cartQuantity = input<number>(0);
|
||||
readonly user = input<AuthUser | null>(null);
|
||||
readonly isAuthenticated = input<boolean>(false);
|
||||
readonly accountNavigationMenus = input<readonly Menu[]>([]);
|
||||
readonly ticketsMenu = input<Menu | null>(null);
|
||||
readonly categories = input<readonly Category[]>([]);
|
||||
readonly displayCategories = input(true);
|
||||
readonly displaySeachBar = input(true);
|
||||
readonly displayCart = input(true);
|
||||
readonly cartClick = output<void>();
|
||||
readonly ticketsClick = output<void>();
|
||||
readonly loginClick = output<void>();
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
.user-dropdown {
|
||||
display: grid;
|
||||
background: #ffffff;
|
||||
border: 1px solid rgba(32, 32, 32, 0.1);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 18px 44px rgba(0, 0, 0, 0.16);
|
||||
padding: 0.75rem;
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
<div class="store-layout d-flex flex-column flex-grow-1">
|
||||
<app-store-header
|
||||
ngSkipHydration
|
||||
[cartQuantity]="cartQuantity()"
|
||||
[logoUrl]="tenant()?.header_logo ?? null"
|
||||
[backgroundImageUrl]="tenant()?.header_bg_image ?? null"
|
||||
[user]="user()"
|
||||
[isAuthenticated]="isAuthenticated()"
|
||||
[accountNavigationMenus]="accountNavigationMenus()"
|
||||
[ticketsMenu]="ticketsMenu() ?? null"
|
||||
[categories]="tenant()?.categories ?? []"
|
||||
[displayCategories]="tenant()?.display_categories ?? true"
|
||||
[displaySeachBar]="tenant()?.display_seach_bar ?? true"
|
||||
[displayCart]="displayCart()"
|
||||
(cartClick)="isCartOpen.set(!isCartOpen())"
|
||||
(ticketsClick)="onTicketsClick()"
|
||||
(loginClick)="onLoginClick()"
|
||||
@@ -15,11 +20,8 @@
|
||||
(categorySelect)="onCategorySelect($event)"
|
||||
/>
|
||||
|
||||
@if (isCartOpen()) {
|
||||
<div
|
||||
class="store-layout__cart-overlay"
|
||||
(click)="isCartOpen.set(false)"
|
||||
></div>
|
||||
@if (displayCart() && isCartOpen()) {
|
||||
<div class="store-layout__cart-overlay" (click)="isCartOpen.set(false)"></div>
|
||||
<div class="store-layout__cart-dropdown card border-0 shadow-lg">
|
||||
<app-cart
|
||||
[showClose]="true"
|
||||
@@ -30,10 +32,7 @@
|
||||
[backgroundColor]="'#ffffff'"
|
||||
(closed)="isCartOpen.set(false)"
|
||||
>
|
||||
<app-button
|
||||
variant="secondary"
|
||||
class="flex-grow-1"
|
||||
(click)="isCartOpen.set(false)"
|
||||
<app-button variant="secondary" class="flex-grow-1" (click)="isCartOpen.set(false)"
|
||||
>Seguir comprando</app-button
|
||||
>
|
||||
<app-button
|
||||
@@ -61,6 +60,7 @@
|
||||
[footerSections]="footerSections()"
|
||||
[socialMedia]="tenant()?.social_media ?? []"
|
||||
[logoUrl]="tenant()?.footer_logo ?? null"
|
||||
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
|
||||
[storeName]="tenant()?.nombre ?? null"
|
||||
(logoutClick)="onLogoutClick()"
|
||||
/>
|
||||
|
||||
@@ -21,14 +21,15 @@
|
||||
|
||||
.store-layout__cart-dropdown {
|
||||
position: absolute;
|
||||
top: 76px;
|
||||
top: 100px;
|
||||
right: calc((100% - 1320px) / 2 + 1.5rem);
|
||||
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
max-height: calc(100vh - 120px);
|
||||
z-index: 1050;
|
||||
background-color: #ffffff;
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(0, 0, 0, 0.08);
|
||||
border: 1px solid var(--border-color);
|
||||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
|
||||
overflow: hidden;
|
||||
animation: store-layout-slide-down 0.2s ease-out;
|
||||
@@ -40,6 +41,7 @@
|
||||
right: 1rem;
|
||||
left: 1rem;
|
||||
width: auto;
|
||||
max-width: none;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,8 @@ const tenant: Tenant = {
|
||||
footer_bg_color: '#313131',
|
||||
header_logo: 'https://example.com/header.png',
|
||||
footer_logo: 'https://example.com/footer.png',
|
||||
header_bg_image: 'https://example.com/header-background.png',
|
||||
footer_bg_image: 'https://example.com/footer-background.png',
|
||||
categories: [],
|
||||
menues: [
|
||||
{
|
||||
@@ -204,6 +206,37 @@ describe('StoreLayoutComponent', () => {
|
||||
expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('hides the configured header elements when the tenant disables them', () => {
|
||||
tenantState.set({
|
||||
...tenant,
|
||||
categories: [{ id: 1, nombre: 'Remeras', subcategories: [] }],
|
||||
display_categories: false,
|
||||
display_seach_bar: false,
|
||||
display_cart: false,
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||
fixture.detectChanges();
|
||||
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
|
||||
expect(compiled.querySelector('#store-search-input')).toBeNull();
|
||||
expect(compiled.querySelector('.store-layout__category-trigger')).toBeNull();
|
||||
expect(compiled.querySelector('app-cart-icon')).toBeNull();
|
||||
|
||||
(fixture.componentInstance as any).isCartOpen.set(true);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(compiled.querySelector('app-cart')).toBeNull();
|
||||
expect(compiled.querySelector('.store-layout__cart-overlay')).toBeNull();
|
||||
|
||||
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
||||
(header.componentInstance as any).toggleMobileMenu();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(compiled.querySelectorAll('.store-layout__mobile-dropdown-item')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders the tenant branding and action icons', () => {
|
||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||
fixture.detectChanges();
|
||||
@@ -222,6 +255,12 @@ describe('StoreLayoutComponent', () => {
|
||||
`app-store-footer img.store-layout__brand-logo[src="${tenant.footer_logo}"]`,
|
||||
),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
(compiled.querySelector('.store-layout__header') as HTMLElement).style.backgroundImage,
|
||||
).toContain(tenant.header_bg_image!);
|
||||
expect(
|
||||
(compiled.querySelector('.store-layout__footer') as HTMLElement).style.backgroundImage,
|
||||
).toContain(tenant.footer_bg_image!);
|
||||
expect(compiled.querySelector('.fa-cart-shopping')).not.toBeNull();
|
||||
expect(compiled.querySelector('.fa-circle-user')).not.toBeNull();
|
||||
expect(compiled.querySelector('.fa-instagram')).not.toBeNull();
|
||||
|
||||
@@ -6,7 +6,7 @@ import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-f
|
||||
import { StoreHeaderComponent } from './store-header/store-header.component';
|
||||
import { CartComponent, CartItemMock } from '../../../shared/components/cart/cart.component';
|
||||
import { ButtonComponent } from '../../../shared/components/button/button.component';
|
||||
import { CartItem } from '../../services/cart/cart.interface';
|
||||
import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface';
|
||||
import { AuthService } from '../../services/auth/auth.service';
|
||||
import { findMenu } from '../../services/menu.utils';
|
||||
import { CheckoutService } from '../../services/checkout.service';
|
||||
@@ -35,6 +35,7 @@ export class StoreLayoutComponent implements OnInit {
|
||||
|
||||
protected readonly isCartOpen = signal(false);
|
||||
protected readonly isCreatingPurchase = signal(false);
|
||||
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
|
||||
|
||||
protected readonly cartSubtotal = computed(() => {
|
||||
const cart = this.cartService.cart();
|
||||
@@ -69,6 +70,18 @@ export class StoreLayoutComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
const variants = item.product?.variants ?? [];
|
||||
const selectedVariant = item.product?.variants?.find(
|
||||
(variant) => variant.id === item.variant_id,
|
||||
);
|
||||
|
||||
if (selectedVariant) {
|
||||
attributes = Object.entries(selectedVariant.values).map(([label, value]) => ({
|
||||
label: this.formatAttributeLabel(label),
|
||||
value: this.formatAttributeValue(value),
|
||||
}));
|
||||
}
|
||||
|
||||
return {
|
||||
cartItemId: item.id,
|
||||
imageUrl: item.product?.imagen ?? null,
|
||||
@@ -78,9 +91,21 @@ export class StoreLayoutComponent implements OnInit {
|
||||
discountPercentage: null,
|
||||
attributes,
|
||||
quantity: item.cantidad,
|
||||
variantId: item.variant_id,
|
||||
variants,
|
||||
};
|
||||
}
|
||||
|
||||
private formatAttributeLabel(value: string): string {
|
||||
const label = value.replace(/[_-]+/g, ' ');
|
||||
return label.charAt(0).toUpperCase() + label.slice(1);
|
||||
}
|
||||
|
||||
private formatAttributeValue(value: CartItemVariantValue): string {
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
return values.map((item) => (typeof item === 'string' ? item : item.label)).join(', ');
|
||||
}
|
||||
|
||||
protected readonly currentYear = new Date().getFullYear();
|
||||
protected readonly tenant = this.tenantService.tenant;
|
||||
protected readonly user = this.authService.user;
|
||||
|
||||
@@ -72,13 +72,13 @@ describe('AuthService', () => {
|
||||
expect(service.token()).toBe('plain-text-token');
|
||||
expect(service.user()?.email).toBe('ada@example.com');
|
||||
expect(service.isAuthenticated()).toBe(true);
|
||||
expect(cookieStore['shopit.auth.token']).toBe('plain-text-token');
|
||||
expect(cookieStore['shopit.front.auth.token']).toBe('plain-text-token');
|
||||
|
||||
httpController.verify();
|
||||
});
|
||||
|
||||
it('hydrates token from cookies and loads the current user during bootstrap', async () => {
|
||||
cookieStore['shopit.auth.token'] = 'persisted-token';
|
||||
cookieStore['shopit.front.auth.token'] = 'persisted-token';
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
@@ -152,7 +152,7 @@ describe('AuthService', () => {
|
||||
});
|
||||
|
||||
it('clears an expired session when /me returns 401', async () => {
|
||||
cookieStore['shopit.auth.token'] = 'expired-token';
|
||||
cookieStore['shopit.front.auth.token'] = 'expired-token';
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
@@ -176,7 +176,7 @@ describe('AuthService', () => {
|
||||
expect(service.user()).toBeNull();
|
||||
expect(service.token()).toBeNull();
|
||||
expect(service.isAuthenticated()).toBe(false);
|
||||
expect(cookieStore['shopit.auth.token']).toBeUndefined();
|
||||
expect(cookieStore['shopit.front.auth.token']).toBeUndefined();
|
||||
|
||||
httpController.verify();
|
||||
});
|
||||
@@ -384,7 +384,7 @@ describe('AuthService', () => {
|
||||
|
||||
expect(service.token()).toBe('plain-text-token');
|
||||
expect(service.user()?.email).toBe('ada@example.com');
|
||||
expect(cookieStore['shopit.auth.token']).toBe('plain-text-token');
|
||||
expect(cookieStore['shopit.front.auth.token']).toBe('plain-text-token');
|
||||
|
||||
httpController.verify();
|
||||
});
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
import { CookieService } from '../cookie/cookie.service';
|
||||
import { TenantService } from '../tenant.service';
|
||||
|
||||
const AUTH_TOKEN_COOKIE_KEY = 'shopit.auth.token';
|
||||
const AUTH_TOKEN_COOKIE_KEY = 'shopit.front.auth.token';
|
||||
const AUTH_USER_SSR_STATE_KEY = makeStateKey<AuthUser>('shopit.auth.user');
|
||||
|
||||
@Injectable({
|
||||
|
||||
@@ -1,6 +1,24 @@
|
||||
export interface CartItemProduct {
|
||||
nombre: string;
|
||||
imagen: string | null;
|
||||
variants?: CartItemVariant[];
|
||||
}
|
||||
|
||||
export interface CartItemVariantOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export type CartItemVariantValue =
|
||||
| string
|
||||
| CartItemVariantOption
|
||||
| Array<string | CartItemVariantOption>;
|
||||
|
||||
export interface CartItemVariant {
|
||||
id: number;
|
||||
precio: string;
|
||||
stock_tecnico: number | null;
|
||||
values: Record<string, CartItemVariantValue>;
|
||||
}
|
||||
|
||||
export interface CartItem {
|
||||
|
||||
@@ -50,9 +50,7 @@ export class CartService extends BaseApiService {
|
||||
): Observable<ApiResponse<Cart>> {
|
||||
this.isUpdatingState.set(true);
|
||||
return this.http
|
||||
.post<
|
||||
ApiResponse<Cart>
|
||||
>(
|
||||
.post<ApiResponse<Cart>>(
|
||||
`${this.tenantApiUrl}/cart/items`,
|
||||
{ catalog_item_id: catalogItemId, variant_id: variantId, cantidad },
|
||||
{
|
||||
@@ -71,21 +69,27 @@ export class CartService extends BaseApiService {
|
||||
);
|
||||
}
|
||||
|
||||
updateItemQuantity(
|
||||
updateItemQuantity(cartItemId: number, cantidad: number): Observable<ApiResponse<Cart>> {
|
||||
return this.updateItem(cartItemId, { cantidad });
|
||||
}
|
||||
|
||||
updateItemVariant(
|
||||
cartItemId: number,
|
||||
cantidad: number,
|
||||
variantId: number,
|
||||
): Observable<ApiResponse<Cart>> {
|
||||
return this.updateItem(cartItemId, { cantidad, variant_id: variantId });
|
||||
}
|
||||
|
||||
private updateItem(
|
||||
cartItemId: number,
|
||||
payload: { cantidad: number; variant_id?: number },
|
||||
): Observable<ApiResponse<Cart>> {
|
||||
this.isUpdatingState.set(true);
|
||||
return this.http
|
||||
.patch<
|
||||
ApiResponse<Cart>
|
||||
>(
|
||||
`${this.tenantApiUrl}/cart/items/${cartItemId}`,
|
||||
{ cantidad },
|
||||
{
|
||||
withCredentials: true,
|
||||
},
|
||||
)
|
||||
.patch<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart/items/${cartItemId}`, payload, {
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
tap((response) => {
|
||||
this.cartState.set(response.data);
|
||||
@@ -101,9 +105,7 @@ export class CartService extends BaseApiService {
|
||||
removeItem(cartItemId: number): Observable<ApiResponse<Cart>> {
|
||||
this.isUpdatingState.set(true);
|
||||
return this.http
|
||||
.delete<
|
||||
ApiResponse<Cart>
|
||||
>(`${this.tenantApiUrl}/cart/items/${cartItemId}`, {
|
||||
.delete<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart/items/${cartItemId}`, {
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { ApiPaginatedResponse } from '../api-paginated-response.interface';
|
||||
|
||||
export type CatalogItemType = 'product' | 'bundle';
|
||||
|
||||
export interface Product {
|
||||
id: number;
|
||||
type: CatalogItemType;
|
||||
category_id: number;
|
||||
brand_id: number | null;
|
||||
slug: string;
|
||||
@@ -15,32 +18,60 @@ export interface Product {
|
||||
|
||||
export interface ProductAttributeOption {
|
||||
id: number;
|
||||
validity_time_id?: number | null;
|
||||
value: string;
|
||||
label: string;
|
||||
sort_order: number;
|
||||
metadata: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export type ProductAttributeType =
|
||||
| 'string'
|
||||
| 'number'
|
||||
| 'boolean'
|
||||
| 'select'
|
||||
| 'multiselect'
|
||||
| 'color'
|
||||
| 'image'
|
||||
| 'event_date';
|
||||
|
||||
export interface ProductAttribute {
|
||||
id: number;
|
||||
codigo: string;
|
||||
nombre: string;
|
||||
is_required: boolean;
|
||||
allow_multi_select?: boolean;
|
||||
show_in_selector?: boolean;
|
||||
metadata_schema: Record<string, unknown> | null;
|
||||
type: string;
|
||||
type: ProductAttributeType;
|
||||
options: ProductAttributeOption[];
|
||||
}
|
||||
|
||||
export type InventoryPolicy = 'tracked' | 'unlimited';
|
||||
|
||||
export interface CatalogVariantOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export type CatalogVariantValue =
|
||||
| string
|
||||
| CatalogVariantOption
|
||||
| Array<string | CatalogVariantOption>;
|
||||
|
||||
export interface CatalogItemVariant {
|
||||
id: number;
|
||||
descripcion?: string | null;
|
||||
precio?: string;
|
||||
event_date_id?: number | null;
|
||||
event_date_ids?: number[];
|
||||
event_dates?: string[];
|
||||
stock_tecnico: number | null;
|
||||
minimum_use_date?: string | null;
|
||||
maximum_use_date?: string | null;
|
||||
effective_minimum_use_date?: string | null;
|
||||
effective_maximum_use_date?: string | null;
|
||||
values: Record<string, string>;
|
||||
values: Record<string, string | string[]>;
|
||||
}
|
||||
|
||||
export interface SelectedCatalogItemVariant extends CatalogItemVariant {
|
||||
@@ -49,6 +80,8 @@ export interface SelectedCatalogItemVariant extends CatalogItemVariant {
|
||||
|
||||
export interface CatalogItemDetail {
|
||||
id: number;
|
||||
type: CatalogItemType;
|
||||
purpose?: 'product' | 'entry';
|
||||
category_id: number | null;
|
||||
brand_id: number | null;
|
||||
slug: string;
|
||||
@@ -58,6 +91,7 @@ export interface CatalogItemDetail {
|
||||
category: string | null;
|
||||
brand: string | null;
|
||||
inventory_policy: InventoryPolicy;
|
||||
max_units_per_user?: number | null;
|
||||
has_tickets: boolean;
|
||||
minimum_use_date: string | null;
|
||||
maximum_use_date: string | null;
|
||||
@@ -68,17 +102,24 @@ export interface CatalogItemDetail {
|
||||
images?: string[];
|
||||
}
|
||||
|
||||
export type CatalogProductLayout = 'row' | 'column_with_image' | 'column_with_cart';
|
||||
export type CatalogGroupLayout = 'paginated' | 'simple' | 'simple_vertical' | 'carousel';
|
||||
export type CatalogProductLayout =
|
||||
| 'row'
|
||||
| 'column_with_image'
|
||||
| 'column_with_cart'
|
||||
| 'ticket_selector';
|
||||
export type CatalogGroupLayout = 'paginated' | 'simple' | 'simple_vertical' | 'carousel' | 'single';
|
||||
|
||||
export interface CatalogFeaturedItemVariant {
|
||||
id: number;
|
||||
descripcion?: string | null;
|
||||
precio?: string;
|
||||
stock_tecnico: number | null;
|
||||
values: Record<string, string>;
|
||||
values: Record<string, CatalogVariantValue>;
|
||||
}
|
||||
|
||||
export interface CatalogFeaturedItem {
|
||||
id: number;
|
||||
type: CatalogItemType;
|
||||
nombre: string;
|
||||
descripcion?: string | null;
|
||||
precio: number | string;
|
||||
|
||||
41
src/app/core/services/checkout.service.spec.ts
Normal file
41
src/app/core/services/checkout.service.spec.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { environment } from '../../../environments/environment';
|
||||
import { CheckoutService } from './checkout.service';
|
||||
|
||||
describe('CheckoutService', () => {
|
||||
let service: CheckoutService;
|
||||
let httpMock: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [CheckoutService, provideHttpClient(), provideHttpClientTesting()],
|
||||
});
|
||||
|
||||
service = TestBed.inject(CheckoutService);
|
||||
httpMock = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => httpMock.verify());
|
||||
|
||||
it('starts one direct checkout with all selected variants', async () => {
|
||||
const payload = {
|
||||
direct_items: [
|
||||
{ catalog_item_id: 10, variant_id: 101, cantidad: 1 },
|
||||
{ catalog_item_id: 10, variant_id: 102, cantidad: 1 },
|
||||
],
|
||||
};
|
||||
const purchasePromise = service.startCheckout('desfile', payload);
|
||||
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
||||
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(payload);
|
||||
|
||||
request.flush({ data: { id: 55 } });
|
||||
|
||||
await expect(purchasePromise).resolves.toMatchObject({ id: 55 });
|
||||
});
|
||||
});
|
||||
@@ -11,16 +11,44 @@ export interface UpdatePurchaseCustomerPayload {
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface DirectCheckoutItem {
|
||||
catalog_item_id: number;
|
||||
variant_id: number | null;
|
||||
cantidad: number;
|
||||
}
|
||||
|
||||
export interface UnavailableCheckoutItem {
|
||||
index: number;
|
||||
catalog_item_id: number;
|
||||
variant_id: number | null;
|
||||
requested_quantity: number;
|
||||
available_quantity: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface InsufficientStockResponse {
|
||||
code: 'purchase.insufficient_stock';
|
||||
message: string;
|
||||
errors: Record<string, string[]>;
|
||||
unavailable_items: UnavailableCheckoutItem[];
|
||||
}
|
||||
|
||||
export function isInsufficientStockResponse(value: unknown): value is InsufficientStockResponse {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
|
||||
const response = value as Partial<InsufficientStockResponse>;
|
||||
|
||||
return (
|
||||
response.code === 'purchase.insufficient_stock' && Array.isArray(response.unavailable_items)
|
||||
);
|
||||
}
|
||||
|
||||
export type StartCheckoutPayload =
|
||||
| {
|
||||
cart_id: number;
|
||||
}
|
||||
| {
|
||||
direct_item: {
|
||||
catalog_item_id: number;
|
||||
variant_id: number | null;
|
||||
cantidad: number;
|
||||
};
|
||||
direct_items: DirectCheckoutItem[];
|
||||
};
|
||||
|
||||
export interface PurchaseStatusResponse {
|
||||
@@ -61,6 +89,7 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
||||
user_id: number;
|
||||
created_at: string | null;
|
||||
payment_method: string | null;
|
||||
expires_at: string | null;
|
||||
dni: string | null;
|
||||
transfer_payer_dni: string | null;
|
||||
telefono: string | null;
|
||||
@@ -180,10 +209,7 @@ export class CheckoutService extends BaseApiService {
|
||||
return purchase;
|
||||
}
|
||||
|
||||
async completePurchase(
|
||||
tenantCode: string,
|
||||
purchaseId: number,
|
||||
): Promise<PurchaseStatusResponse> {
|
||||
async completePurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||
const response = await firstValueFrom(
|
||||
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
|
||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/complete`,
|
||||
@@ -221,10 +247,7 @@ export class CheckoutService extends BaseApiService {
|
||||
return { status: purchase.status ?? null };
|
||||
}
|
||||
|
||||
async cancelPurchase(
|
||||
tenantCode: string,
|
||||
purchaseId: number,
|
||||
): Promise<PurchaseStatusResponse> {
|
||||
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||
const response = await firstValueFrom(
|
||||
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
|
||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/cancel`,
|
||||
@@ -248,9 +271,7 @@ export class CheckoutService extends BaseApiService {
|
||||
if (status) {
|
||||
url += `?status=${status}`;
|
||||
}
|
||||
const response = await firstValueFrom(
|
||||
this.http.get<{ data: PurchaseSummaryResponse[] }>(url),
|
||||
);
|
||||
const response = await firstValueFrom(this.http.get<{ data: PurchaseSummaryResponse[] }>(url));
|
||||
if (!response) {
|
||||
throw new Error('Error al obtener las compras.');
|
||||
}
|
||||
|
||||
@@ -163,6 +163,8 @@ describe('ModalService', () => {
|
||||
const activeModal = service.activeModal();
|
||||
const resultPromise = firstValueFrom(result$);
|
||||
|
||||
expect(activeModal?.config.size).toBe('sm');
|
||||
|
||||
activeModal?.ref.dismiss('escape');
|
||||
|
||||
await expect(resultPromise).resolves.toBe(false);
|
||||
|
||||
@@ -166,7 +166,10 @@ export class ModalService {
|
||||
}
|
||||
|
||||
openConfirmDeleteRef(config: ConfirmModalConfig): ModalRef<boolean> {
|
||||
return this.open(ConfirmDeleteModalComponent, this.buildConfirmModalConfig(config));
|
||||
return this.open(
|
||||
ConfirmDeleteModalComponent,
|
||||
this.buildConfirmModalConfig({ size: 'sm', ...config }),
|
||||
);
|
||||
}
|
||||
|
||||
openSimple(config: SimpleModalConfig): Observable<void> {
|
||||
|
||||
@@ -9,18 +9,62 @@ export interface BankAccount {
|
||||
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 {
|
||||
background_image?: string | null;
|
||||
background_image_id?: string | null;
|
||||
title_html?: string | null;
|
||||
description_html?: string | null;
|
||||
button_text?: 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 {
|
||||
id?: number;
|
||||
title?: 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 {
|
||||
@@ -52,6 +96,8 @@ export interface Tenant {
|
||||
codigo: string;
|
||||
nombre: string;
|
||||
dominio: string;
|
||||
site_title?: string | null;
|
||||
favicon?: string | null;
|
||||
primary_color: string;
|
||||
secondary_color: string;
|
||||
danger_color: string;
|
||||
@@ -60,14 +106,21 @@ export interface Tenant {
|
||||
footer_bg_color: string;
|
||||
header_logo: string;
|
||||
footer_logo: string;
|
||||
header_bg_image?: string | null;
|
||||
footer_bg_image?: string | null;
|
||||
website_type_code?: string | null;
|
||||
website_type?: WebsiteType | null;
|
||||
event_date_text?: string | null;
|
||||
extras?: WebsiteExtras;
|
||||
event?: TenantEvent | null;
|
||||
selected_bank_account_id?: number | 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_group_layout?: 'paginated' | 'simple' | 'simple_vertical' | 'carousel';
|
||||
search_product_layout?: 'row' | 'column_with_image' | 'column_with_cart' | 'ticket_selector';
|
||||
search_group_layout?: 'paginated' | 'simple' | 'simple_vertical' | 'carousel' | 'single';
|
||||
search_items_per_page?: number;
|
||||
main_carousel_images?: string[];
|
||||
display_categories?: boolean;
|
||||
display_seach_bar?: boolean;
|
||||
display_cart?: boolean;
|
||||
social_media?: SocialMedia[];
|
||||
menues?: Menu[];
|
||||
categories: Category[];
|
||||
|
||||
@@ -754,6 +754,29 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
class="component-demo component-demo--ticket-selector card shadow-sm mt-4"
|
||||
data-testid="ticket-selector-demo"
|
||||
>
|
||||
<div class="card-body">
|
||||
<span class="eyebrow">Reusable Component</span>
|
||||
<h2 class="mb-2">Selector de entradas (Ticket Selector Layout)</h2>
|
||||
<p class="text-muted mb-4">
|
||||
Demo de selección encadenada por tipo, sector, fila y asiento. Las combinaciones sin stock
|
||||
no aparecen como disponibles.
|
||||
</p>
|
||||
|
||||
<app-product-ticket-selector
|
||||
[title]="testTicketSelectorProduct.title"
|
||||
[description]="testTicketSelectorProduct.description"
|
||||
[price]="testTicketSelectorProduct.price"
|
||||
[imageUrl]="testTicketSelectorProduct.imageUrl"
|
||||
[variants]="testTicketSelectorProduct.variants"
|
||||
(buy)="onTicketBuy($event)"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<app-store-section title="PRODUCTOS" class="component-demo store-section-demo mt-5">
|
||||
<div class="row">
|
||||
@for (product of testProducts; track product.title) {
|
||||
|
||||
@@ -15,6 +15,10 @@
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.component-demo--ticket-selector {
|
||||
width: min(100%, 76rem);
|
||||
}
|
||||
|
||||
.store-section-demo {
|
||||
width: min(100%, 64rem);
|
||||
}
|
||||
@@ -77,7 +81,7 @@ h1 {
|
||||
|
||||
.modal-showcase__result {
|
||||
padding: 0.875rem 1rem;
|
||||
border: 1px dashed rgba(32, 32, 32, 0.14);
|
||||
border: 1px dashed var(--border-color);
|
||||
border-radius: 0.875rem;
|
||||
background: linear-gradient(180deg, rgba(248, 248, 248, 0.92), rgba(255, 255, 255, 0.98));
|
||||
color: #495057;
|
||||
@@ -231,7 +235,7 @@ h1 {
|
||||
justify-content: center;
|
||||
height: 120px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #dee2e6;
|
||||
border: 1px solid var(--border-color);
|
||||
padding: 1rem;
|
||||
overflow: hidden;
|
||||
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
|
||||
@@ -281,7 +285,7 @@ h1 {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #dee2e6;
|
||||
border: 1px solid var(--border-color);
|
||||
overflow: hidden;
|
||||
background-color: #ffffff;
|
||||
transition:
|
||||
@@ -296,7 +300,7 @@ h1 {
|
||||
&__preview {
|
||||
height: 80px;
|
||||
width: 100%;
|
||||
border-bottom: 1px solid #dee2e6;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
transition: opacity 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
@@ -337,7 +341,7 @@ h1 {
|
||||
background-color: #eaeaea;
|
||||
padding: 1.5rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #dee2e6;
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
&__row {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { InputComponent } from '../../../../shared/components/input/input.compon
|
||||
import { PaginatorComponent } from '../../../../shared/components/paginator/paginator.component';
|
||||
import { ProductColumnWithImageComponent } from '../../../../shared/components/product-column-with-image/product-column-with-image.component';
|
||||
import { ProductRowCardComponent } from '../../../../shared/components/product-row-card/product-row-card.component';
|
||||
import { ProductTicketSelectorComponent } from '../../../../shared/components/product-ticket-selector/product-ticket-selector.component';
|
||||
import { ProductVerticalWithCartCardComponent } from '../../../../shared/components/product-vertical-with-cart-card/product-vertical-with-cart-card.component';
|
||||
import { StoreSectionComponent } from '../../../../shared/components/store-section/store-section.component';
|
||||
import { ModalService } from '../../../../core/services/modal.service';
|
||||
@@ -32,6 +33,11 @@ interface CarouselProductMock {
|
||||
imageUrl: string;
|
||||
}
|
||||
|
||||
const ticketOption = (value: string, label: string = value): { value: string; label: string } => ({
|
||||
value,
|
||||
label,
|
||||
});
|
||||
|
||||
@Component({
|
||||
selector: 'app-reutilizables-test-page',
|
||||
imports: [
|
||||
@@ -41,6 +47,7 @@ interface CarouselProductMock {
|
||||
PaginatorComponent,
|
||||
ProductColumnWithImageComponent,
|
||||
ProductRowCardComponent,
|
||||
ProductTicketSelectorComponent,
|
||||
ProductVerticalWithCartCardComponent,
|
||||
StoreSectionComponent,
|
||||
IconButtonComponent,
|
||||
@@ -204,8 +211,9 @@ export class ReutilizablesTestPageComponent {
|
||||
'Acceso total al predio. No incluye acceso a estacionamiento. Niños menores de 5 años ingresan gratis.',
|
||||
price: 10000,
|
||||
variants: [
|
||||
{ label: '10 de Octubre', value: '10-oct' },
|
||||
{ label: '11 de Octubre', value: '11-oct' },
|
||||
{ id: '10-oct-manana', values: { fecha: '10 de Octubre', turno: 'Mañana' } },
|
||||
{ id: '10-oct-tarde', values: { fecha: '10 de Octubre', turno: 'Tarde' } },
|
||||
{ id: '11-oct-tarde', values: { fecha: '11 de Octubre', turno: 'Tarde' } },
|
||||
],
|
||||
};
|
||||
|
||||
@@ -215,6 +223,125 @@ export class ReutilizablesTestPageComponent {
|
||||
price: 11500,
|
||||
};
|
||||
|
||||
protected readonly testTicketSelectorProduct = {
|
||||
title: 'ENTRADAS DESFILE PURA TENDENCIA',
|
||||
description: '',
|
||||
price: 40000,
|
||||
imageUrl: '/images/ticket-selector-entrada-pasarela.png',
|
||||
variants: [
|
||||
{
|
||||
id: 1001,
|
||||
precio: 250000,
|
||||
stock_tecnico: 1,
|
||||
values: {
|
||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||
sector: ticketOption('a', 'Sector A'),
|
||||
fila: ticketOption('1', 'Fila 1'),
|
||||
asiento: ticketOption('1', 'Asiento 1'),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 1002,
|
||||
precio: 250000,
|
||||
stock_tecnico: 1,
|
||||
values: {
|
||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||
sector: ticketOption('a', 'Sector A'),
|
||||
fila: ticketOption('1', 'Fila 1'),
|
||||
asiento: ticketOption('2', 'Asiento 2'),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 1003,
|
||||
precio: 250000,
|
||||
stock_tecnico: 1,
|
||||
values: {
|
||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||
sector: ticketOption('c', 'Sector C'),
|
||||
fila: ticketOption('1', 'Fila 1'),
|
||||
asiento: ticketOption('1', 'Asiento 1'),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 1004,
|
||||
precio: 200000,
|
||||
stock_tecnico: 1,
|
||||
values: {
|
||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||
sector: ticketOption('a', 'Sector A'),
|
||||
fila: ticketOption('2', 'Fila 2'),
|
||||
asiento: ticketOption('1', 'Asiento 1'),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 1005,
|
||||
precio: 200000,
|
||||
stock_tecnico: 0,
|
||||
values: {
|
||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||
sector: ticketOption('a', 'Sector A'),
|
||||
fila: ticketOption('2', 'Fila 2'),
|
||||
asiento: ticketOption('2', 'Asiento 2'),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 1006,
|
||||
precio: 100000,
|
||||
stock_tecnico: 1,
|
||||
values: {
|
||||
tipo: ticketOption('general', 'General'),
|
||||
sector: ticketOption('b', 'Sector B'),
|
||||
fila: ticketOption('3', 'Fila 3'),
|
||||
asiento: ticketOption('1', 'Asiento 1'),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 1007,
|
||||
precio: 100000,
|
||||
stock_tecnico: 1,
|
||||
values: {
|
||||
tipo: ticketOption('general', 'General'),
|
||||
sector: ticketOption('b', 'Sector B'),
|
||||
fila: ticketOption('3', 'Fila 3'),
|
||||
asiento: ticketOption('2', 'Asiento 2'),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 1008,
|
||||
precio: 90000,
|
||||
stock_tecnico: 1,
|
||||
values: {
|
||||
tipo: ticketOption('general', 'General'),
|
||||
sector: ticketOption('d', 'Sector D'),
|
||||
fila: ticketOption('3', 'Fila 3'),
|
||||
asiento: ticketOption('1', 'Asiento 1'),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 1009,
|
||||
precio: 65000,
|
||||
stock_tecnico: 1,
|
||||
values: {
|
||||
tipo: ticketOption('general', 'General'),
|
||||
sector: ticketOption('d', 'Sector D'),
|
||||
fila: ticketOption('4', 'Fila 4'),
|
||||
asiento: ticketOption('1', 'Asiento 1'),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 1010,
|
||||
precio: 40000,
|
||||
stock_tecnico: 1,
|
||||
values: {
|
||||
tipo: ticketOption('general', 'General'),
|
||||
sector: ticketOption('d', 'Sector D'),
|
||||
fila: ticketOption('5', 'Fila 5'),
|
||||
asiento: ticketOption('1', 'Asiento 1'),
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
protected readonly cartMockItems: CartItemMock[] = [
|
||||
{
|
||||
imageUrl: null,
|
||||
@@ -271,6 +398,12 @@ export class ReutilizablesTestPageComponent {
|
||||
alert(`Comprando: ${productTitle}`);
|
||||
}
|
||||
|
||||
protected onTicketBuy(variantIds: number[]): void {
|
||||
this.toastService.success(
|
||||
`Compra iniciada para ${variantIds.length} entrada/s: ${variantIds.join(', ')}.`,
|
||||
);
|
||||
}
|
||||
|
||||
protected onFileChange(file: File | null): void {
|
||||
this.fileName = file?.name ?? '';
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<div class="attribute-selector">
|
||||
@for (attribute of attributes(); track attribute.id) {
|
||||
@for (attribute of visibleAttributes(); track attribute.codigo) {
|
||||
<div class="attribute-selector__row">
|
||||
<span class="attribute-selector__label">{{ attribute.nombre }}:</span>
|
||||
|
||||
@@ -10,12 +10,14 @@
|
||||
type="button"
|
||||
class="attribute-selector__swatch"
|
||||
[class.attribute-selector__swatch--selected]="hasSelectedOption(attribute, option)"
|
||||
[class.attribute-selector__swatch--disabled]="!availableOptions()[attribute.id][option.id]"
|
||||
[class.attribute-selector__swatch--disabled]="
|
||||
!availableOptions()[attribute.codigo][option.id]
|
||||
"
|
||||
[style.background-color]="getOptionSwatchColor(option)"
|
||||
[attr.aria-label]="option.label"
|
||||
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
||||
[title]="option.label"
|
||||
[disabled]="!availableOptions()[attribute.id][option.id]"
|
||||
[disabled]="!availableOptions()[attribute.codigo][option.id]"
|
||||
(click)="selectAttributeOption(attribute, option)"
|
||||
>
|
||||
<span class="visually-hidden">{{ option.label }}</span>
|
||||
@@ -24,10 +26,14 @@
|
||||
<button
|
||||
type="button"
|
||||
class="attribute-selector__text-option"
|
||||
[class.attribute-selector__text-option--selected]="hasSelectedOption(attribute, option)"
|
||||
[class.attribute-selector__text-option--disabled]="!availableOptions()[attribute.id][option.id]"
|
||||
[class.attribute-selector__text-option--selected]="
|
||||
hasSelectedOption(attribute, option)
|
||||
"
|
||||
[class.attribute-selector__text-option--disabled]="
|
||||
!availableOptions()[attribute.codigo][option.id]
|
||||
"
|
||||
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
||||
[disabled]="!availableOptions()[attribute.id][option.id]"
|
||||
[disabled]="!availableOptions()[attribute.codigo][option.id]"
|
||||
(click)="selectAttributeOption(attribute, option)"
|
||||
>
|
||||
{{ option.label }}
|
||||
|
||||
@@ -54,7 +54,7 @@
|
||||
}
|
||||
|
||||
&__text-option {
|
||||
border: 1px solid #dcdcdc;
|
||||
border: 1px solid var(--border-color);
|
||||
background: #ffffff;
|
||||
color: #666666;
|
||||
transition: border-color 0.2s ease, color 0.2s ease, background-color 0.2s ease;
|
||||
|
||||
@@ -68,4 +68,85 @@ describe('ProductAttributeSelectorComponent', () => {
|
||||
expect(buttons[0].disabled).toBe(true);
|
||||
expect(buttons[1].disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('allows multiple event dates and emits the exact matching variant', () => {
|
||||
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
||||
const emittedIds: Array<number | null> = [];
|
||||
fixture.componentInstance.variantChange.subscribe((variant) =>
|
||||
emittedIds.push(variant?.id ?? null),
|
||||
);
|
||||
fixture.componentRef.setInput('attributes', [
|
||||
{
|
||||
id: 2,
|
||||
codigo: 'event_date',
|
||||
nombre: 'Fecha',
|
||||
is_required: true,
|
||||
allow_multi_select: true,
|
||||
metadata_schema: null,
|
||||
type: 'event_date',
|
||||
options: [
|
||||
{ id: 101, value: '1', label: '09/10/2026', sort_order: 0, metadata: null },
|
||||
{ id: 102, value: '2', label: '10/10/2026', sort_order: 1, metadata: null },
|
||||
],
|
||||
} satisfies ProductAttribute,
|
||||
]);
|
||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{ id: 1, stock_tecnico: null, values: { event_date: '1' } },
|
||||
{ id: 2, stock_tecnico: null, values: { event_date: '2' } },
|
||||
{ id: 3, stock_tecnico: null, values: { event_date: ['1', '2'] } },
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
const buttons = Array.from(
|
||||
fixture.nativeElement.querySelectorAll('.attribute-selector__text-option'),
|
||||
) as HTMLButtonElement[];
|
||||
buttons[0].click();
|
||||
fixture.detectChanges();
|
||||
buttons[1].click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(buttons[0].getAttribute('aria-pressed')).toBe('true');
|
||||
expect(buttons[1].getAttribute('aria-pressed')).toBe('true');
|
||||
expect(emittedIds).toContain(3);
|
||||
});
|
||||
|
||||
it('hides configured attributes and matches variants using only visible selections', () => {
|
||||
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
||||
const emittedIds: Array<number | null> = [];
|
||||
fixture.componentInstance.variantChange.subscribe((variant) =>
|
||||
emittedIds.push(variant?.id ?? null),
|
||||
);
|
||||
fixture.componentRef.setInput('attributes', [
|
||||
sizeAttribute,
|
||||
{
|
||||
id: 2,
|
||||
codigo: 'internal_type',
|
||||
nombre: 'Internal type',
|
||||
is_required: true,
|
||||
show_in_selector: false,
|
||||
metadata_schema: null,
|
||||
type: 'select',
|
||||
options: [
|
||||
{ id: 30, value: 'adult', label: 'Adult', sort_order: 0, metadata: null },
|
||||
{ id: 40, value: 'child', label: 'Child', sort_order: 1, metadata: null },
|
||||
],
|
||||
} satisfies ProductAttribute,
|
||||
]);
|
||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{ id: 1, stock_tecnico: null, values: { size: 'S', internal_type: 'adult' } },
|
||||
{ id: 2, stock_tecnico: null, values: { size: 'M', internal_type: 'child' } },
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
const labels = fixture.nativeElement.querySelectorAll('.attribute-selector__label');
|
||||
const buttons = fixture.nativeElement.querySelectorAll('.attribute-selector__text-option');
|
||||
|
||||
expect(labels).toHaveLength(1);
|
||||
expect(labels[0].textContent).toContain('Size');
|
||||
buttons[1].click();
|
||||
fixture.detectChanges();
|
||||
expect(emittedIds).toContain(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -32,48 +32,69 @@ export class ProductAttributeSelectorComponent {
|
||||
|
||||
public variantChange = output<CatalogItemVariant | null>();
|
||||
|
||||
protected readonly selectedAttributeOptions = signal<Record<number, number>>({});
|
||||
protected readonly visibleAttributes = computed(() =>
|
||||
this.attributes().filter((attribute) => attribute.show_in_selector !== false),
|
||||
);
|
||||
|
||||
protected readonly selectedAttributeOptions = signal<Record<string, number[]>>({});
|
||||
|
||||
protected readonly availableOptions = computed(() => {
|
||||
const selections = this.selectedAttributeOptions();
|
||||
const variants = this.variants();
|
||||
const attributes = this.attributes();
|
||||
const attributes = this.visibleAttributes();
|
||||
|
||||
const availability: Record<number, Record<number, boolean>> = {};
|
||||
const availability: Record<string, Record<number, boolean>> = {};
|
||||
|
||||
for (const attribute of attributes) {
|
||||
availability[attribute.id] = {};
|
||||
availability[attribute.codigo] = {};
|
||||
for (const option of attribute.options) {
|
||||
const optionNormalized = this.normalizeText(option.value || option.label);
|
||||
const selectedForAttribute = selections[attribute.codigo] ?? [];
|
||||
|
||||
if (
|
||||
!attribute.allow_multi_select &&
|
||||
selectedForAttribute.length >= 1 &&
|
||||
!selectedForAttribute.includes(option.id)
|
||||
) {
|
||||
availability[attribute.codigo][option.id] = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
const isAvailable = variants.some((variant) => {
|
||||
if (!this.isVariantAvailable(variant)) return false;
|
||||
|
||||
const variantAttrValue = this.getDefaultVariantAttributeValue(attribute, variant.values);
|
||||
if (!variantAttrValue || this.normalizeText(variantAttrValue) !== optionNormalized) {
|
||||
const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values);
|
||||
const desiredOptionIds = selectedForAttribute.includes(option.id)
|
||||
? selectedForAttribute
|
||||
: [...selectedForAttribute, option.id];
|
||||
const desiredValues = desiredOptionIds
|
||||
.map((id) => attribute.options.find((candidate) => candidate.id === id))
|
||||
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
|
||||
.map((candidate) => this.normalizeText(candidate.value || candidate.label));
|
||||
|
||||
if (
|
||||
!variantAttrValues.includes(optionNormalized) ||
|
||||
!desiredValues.every((value) => variantAttrValues.includes(value))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const otherAttr of attributes) {
|
||||
if (otherAttr.id === attribute.id) continue;
|
||||
const selectedOptionId = selections[otherAttr.id];
|
||||
if (selectedOptionId !== undefined) {
|
||||
const selectedOption = otherAttr.options.find((o) => o.id === selectedOptionId);
|
||||
if (selectedOption) {
|
||||
const selectedNormalized = this.normalizeText(
|
||||
selectedOption.value || selectedOption.label,
|
||||
);
|
||||
const vAttrValue = this.getDefaultVariantAttributeValue(otherAttr, variant.values);
|
||||
if (!vAttrValue || this.normalizeText(vAttrValue) !== selectedNormalized) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (otherAttr.codigo === attribute.codigo) continue;
|
||||
const selectedOptionIds = selections[otherAttr.codigo] ?? [];
|
||||
const selectedValues = selectedOptionIds
|
||||
.map((id) => otherAttr.options.find((candidate) => candidate.id === id))
|
||||
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
|
||||
.map((candidate) => this.normalizeText(candidate.value || candidate.label));
|
||||
const variantValues = this.getVariantAttributeValues(otherAttr, variant.values);
|
||||
if (!selectedValues.every((value) => variantValues.includes(value))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
availability[attribute.id][option.id] = isAvailable;
|
||||
availability[attribute.codigo][option.id] = isAvailable;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +107,7 @@ export class ProductAttributeSelectorComponent {
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const attributes = this.attributes();
|
||||
const attributes = this.visibleAttributes();
|
||||
const defaultVariant = this.selectedVariant();
|
||||
|
||||
untracked(() => {
|
||||
@@ -97,7 +118,7 @@ export class ProductAttributeSelectorComponent {
|
||||
effect(() => {
|
||||
const selections = this.selectedAttributeOptions();
|
||||
const variants = this.variants();
|
||||
const attributes = this.attributes();
|
||||
const attributes = this.visibleAttributes();
|
||||
|
||||
untracked(() => {
|
||||
this.emitMatchingVariant(selections, variants, attributes);
|
||||
@@ -109,17 +130,28 @@ export class ProductAttributeSelectorComponent {
|
||||
attribute: ProductAttribute,
|
||||
option: ProductAttributeOption,
|
||||
): boolean {
|
||||
return this.selectedAttributeOptions()[attribute.id] === option.id;
|
||||
return (this.selectedAttributeOptions()[attribute.codigo] ?? []).includes(option.id);
|
||||
}
|
||||
|
||||
protected selectAttributeOption(
|
||||
attribute: ProductAttribute,
|
||||
option: ProductAttributeOption,
|
||||
): void {
|
||||
this.selectedAttributeOptions.update((current) => ({
|
||||
...current,
|
||||
[attribute.id]: option.id,
|
||||
}));
|
||||
this.selectedAttributeOptions.update((current) => {
|
||||
const selected = current[attribute.codigo] ?? [];
|
||||
const isMultiple = attribute.allow_multi_select ?? false;
|
||||
let next: number[];
|
||||
|
||||
if (!isMultiple) {
|
||||
next = [option.id];
|
||||
} else if (selected.includes(option.id)) {
|
||||
next = selected.filter((id) => id !== option.id);
|
||||
} else {
|
||||
next = [...selected, option.id];
|
||||
}
|
||||
|
||||
return { ...current, [attribute.codigo]: next };
|
||||
});
|
||||
}
|
||||
|
||||
protected isColorOption(option: ProductAttributeOption): boolean {
|
||||
@@ -134,51 +166,44 @@ export class ProductAttributeSelectorComponent {
|
||||
attributes: ProductAttribute[],
|
||||
defaultVariant: CatalogItemVariant | null,
|
||||
): void {
|
||||
const selections: Record<number, number> = {};
|
||||
const selections: Record<string, number[]> = {};
|
||||
|
||||
for (const attribute of attributes) {
|
||||
const optionId = this.findDefaultOptionId(attribute, defaultVariant);
|
||||
if (optionId !== null) {
|
||||
selections[attribute.id] = optionId;
|
||||
const optionIds = this.findDefaultOptionIds(attribute, defaultVariant);
|
||||
if (optionIds.length > 0) {
|
||||
selections[attribute.codigo] = optionIds;
|
||||
}
|
||||
}
|
||||
|
||||
this.selectedAttributeOptions.set(selections);
|
||||
}
|
||||
|
||||
private findDefaultOptionId(
|
||||
private findDefaultOptionIds(
|
||||
attribute: ProductAttribute,
|
||||
variant: CatalogItemVariant | null,
|
||||
): number | null {
|
||||
): number[] {
|
||||
if (!variant) {
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
|
||||
const defaultValue = this.getDefaultVariantAttributeValue(attribute, variant.values);
|
||||
if (!defaultValue) {
|
||||
return null;
|
||||
const defaultValues = this.getVariantAttributeValues(attribute, variant.values);
|
||||
if (defaultValues.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const normalizedValue = this.normalizeText(defaultValue);
|
||||
const matchByValue = attribute.options.find(
|
||||
(option) => this.normalizeText(option.value) === normalizedValue,
|
||||
);
|
||||
|
||||
if (matchByValue) {
|
||||
return matchByValue.id;
|
||||
}
|
||||
|
||||
const matchByLabel = attribute.options.find(
|
||||
(option) => this.normalizeText(option.label) === normalizedValue,
|
||||
);
|
||||
|
||||
return matchByLabel?.id ?? null;
|
||||
return attribute.options
|
||||
.filter(
|
||||
(option) =>
|
||||
defaultValues.includes(this.normalizeText(option.value)) ||
|
||||
defaultValues.includes(this.normalizeText(option.label)),
|
||||
)
|
||||
.map((option) => option.id);
|
||||
}
|
||||
|
||||
private getDefaultVariantAttributeValue(
|
||||
private getVariantAttributeValues(
|
||||
attribute: ProductAttribute,
|
||||
variantAttributes: Record<string, string>,
|
||||
): string | null {
|
||||
variantAttributes: Record<string, string | string[]>,
|
||||
): string[] {
|
||||
const normalizedCodigo = this.normalizeText(attribute.codigo);
|
||||
const normalizedNombre = this.normalizeText(attribute.nombre);
|
||||
|
||||
@@ -186,11 +211,11 @@ export class ProductAttributeSelectorComponent {
|
||||
const normalizedKey = this.normalizeText(key);
|
||||
|
||||
if (normalizedKey === normalizedCodigo || normalizedKey === normalizedNombre) {
|
||||
return value;
|
||||
return (Array.isArray(value) ? value : [value]).map((item) => this.normalizeText(item));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
|
||||
private normalizeText(value: string | null | undefined): string {
|
||||
@@ -234,7 +259,7 @@ export class ProductAttributeSelectorComponent {
|
||||
}
|
||||
|
||||
private emitMatchingVariant(
|
||||
selections: Record<number, number>,
|
||||
selections: Record<string, number[]>,
|
||||
variants: CatalogItemVariant[],
|
||||
attributes: ProductAttribute[],
|
||||
): void {
|
||||
@@ -243,18 +268,22 @@ export class ProductAttributeSelectorComponent {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedValuesById: Record<number, string> = {};
|
||||
const selectedValuesByCode: Record<string, string[]> = {};
|
||||
let allSelected = true;
|
||||
for (const attr of attributes) {
|
||||
const selectedOptionId = selections[attr.id];
|
||||
if (selectedOptionId === undefined) {
|
||||
const selectedOptionIds = selections[attr.codigo] ?? [];
|
||||
if (
|
||||
selectedOptionIds.length === 0 ||
|
||||
(!attr.allow_multi_select && selectedOptionIds.length !== 1)
|
||||
) {
|
||||
allSelected = false;
|
||||
break;
|
||||
}
|
||||
const option = attr.options.find((o) => o.id === selectedOptionId);
|
||||
if (option) {
|
||||
selectedValuesById[attr.id] = this.normalizeText(option.value || option.label);
|
||||
}
|
||||
selectedValuesByCode[attr.codigo] = selectedOptionIds
|
||||
.map((id) => attr.options.find((option) => option.id === id))
|
||||
.filter((option): option is ProductAttributeOption => option !== undefined)
|
||||
.map((option) => this.normalizeText(option.value || option.label))
|
||||
.sort();
|
||||
}
|
||||
|
||||
if (!allSelected) {
|
||||
@@ -264,10 +293,12 @@ export class ProductAttributeSelectorComponent {
|
||||
|
||||
const matchingVariant = variants.find((variant) => {
|
||||
return attributes.every((attr) => {
|
||||
const selectedValue = selectedValuesById[attr.id];
|
||||
const variantValue = this.getDefaultVariantAttributeValue(attr, variant.values);
|
||||
if (!variantValue) return false;
|
||||
return this.normalizeText(variantValue) === selectedValue;
|
||||
const selectedValues = selectedValuesByCode[attr.codigo];
|
||||
const variantValues = this.getVariantAttributeValues(attr, variant.values).sort();
|
||||
return (
|
||||
selectedValues.length === variantValues.length &&
|
||||
selectedValues.every((value, index) => value === variantValues[index])
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
:host {
|
||||
display: block;
|
||||
border-bottom: 1px solid #dddddd;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
:host(:last-child) {
|
||||
@@ -24,7 +24,7 @@
|
||||
aspect-ratio: 4 / 3;
|
||||
border-radius: 5px 0 0 5px;
|
||||
background-color: #ffffff;
|
||||
border: 1px solid #eaeaea;
|
||||
border: 1px solid var(--border-color);
|
||||
overflow: hidden;
|
||||
|
||||
img {
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1rem 0;
|
||||
border-bottom: 1px solid #DDDDDD;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.skeleton-item:last-child {
|
||||
|
||||
@@ -74,6 +74,7 @@
|
||||
|
||||
.ticket__actions {
|
||||
display: flex;
|
||||
grid-column: 4;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
@@ -91,6 +92,10 @@
|
||||
color: #8a8a8a;
|
||||
}
|
||||
|
||||
.ticket--disabled .ticket__actions {
|
||||
grid-column: 3;
|
||||
}
|
||||
|
||||
:host ::ng-deep .ticket--disabled button.ticket__qr-button:disabled {
|
||||
--bs-btn-disabled-bg: #8a8a8a;
|
||||
--bs-btn-disabled-border-color: #8a8a8a;
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
.tickets-list__generating-spinner {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: 3px solid #dce8e0;
|
||||
border: 3px solid var(--border-color);
|
||||
border-top-color: var(--tenant-primary, #009933);
|
||||
border-radius: 50%;
|
||||
animation: tickets-spinner 0.75s linear infinite;
|
||||
@@ -39,7 +39,7 @@
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px solid #dddddd;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.tickets-list__header--inactive {
|
||||
@@ -89,7 +89,7 @@
|
||||
}
|
||||
|
||||
.tickets-list app-ticket {
|
||||
border-bottom: 1px solid #dddddd;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.tickets-list__empty {
|
||||
@@ -104,7 +104,7 @@
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px solid #dddddd;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.tickets-list__skeleton-selection,
|
||||
@@ -130,7 +130,7 @@
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid #dddddd;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.tickets-list__skeleton-check,
|
||||
|
||||
@@ -127,11 +127,13 @@ export class CategoryItemsPageComponent {
|
||||
this.creatingDirectPurchase.set(true);
|
||||
try {
|
||||
const purchase = await this.injector.get(CheckoutService).startCheckout(tenant.codigo, {
|
||||
direct_item: {
|
||||
catalog_item_id: event.product.id,
|
||||
variant_id: event.variant ?? null,
|
||||
cantidad: event.quantity,
|
||||
},
|
||||
direct_items: [
|
||||
{
|
||||
catalog_item_id: event.product.id,
|
||||
variant_id: event.variant ?? null,
|
||||
cantidad: event.quantity,
|
||||
},
|
||||
],
|
||||
});
|
||||
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
||||
} catch (error) {
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
.checkout-page__spinner {
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
border: 0.25rem solid rgba(32, 32, 32, 0.08);
|
||||
border: 0.25rem solid var(--border-color);
|
||||
border-top-color: var(--tenant-primary);
|
||||
border-radius: 50%;
|
||||
animation: checkout-page-spin 0.8s linear infinite;
|
||||
|
||||
@@ -60,7 +60,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
qr_data: { qr_code: 'qr-value' },
|
||||
}),
|
||||
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'in_review' }),
|
||||
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||
withCustomLoading: vi.fn(),
|
||||
};
|
||||
checkoutServiceStub.withCustomLoading.mockReturnValue(checkoutServiceStub);
|
||||
@@ -199,20 +199,20 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
component.selectedPaymentMethod.set('transfer');
|
||||
|
||||
await component.onComplete();
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(1);
|
||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
|
||||
expect(component.transferValidationStatus()).toBe('pending');
|
||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(1);
|
||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
|
||||
|
||||
await component.onComplete();
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(1);
|
||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('navigates after a transfer is confirmed as paid', async () => {
|
||||
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'paid' });
|
||||
checkoutServiceStub.submitPurchaseForReview.mockResolvedValue({ status: 'paid' });
|
||||
const { component } = createComponent();
|
||||
component.selectedPaymentMethod.set('transfer');
|
||||
|
||||
@@ -375,7 +375,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
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',
|
||||
async (status) => {
|
||||
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 () => {
|
||||
const updatedPurchase = {
|
||||
id: 25,
|
||||
|
||||
@@ -437,7 +437,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
.withCustomLoading()
|
||||
.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);
|
||||
return;
|
||||
}
|
||||
@@ -576,7 +580,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
.getPurchase(tenant.codigo, purchaseId);
|
||||
|
||||
if (
|
||||
purchase.status === 'in_review' ||
|
||||
(purchase.status === 'pending_payment' && purchase.expires_at === null) ||
|
||||
purchase.status === 'paid' ||
|
||||
purchase.status === 'cancelled' ||
|
||||
purchase.status === 'rejected' ||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
.faq-page__empty {
|
||||
padding: 1rem 0;
|
||||
border-bottom: 1px solid #dedede;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
color: #888888;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
@@ -31,6 +31,6 @@
|
||||
.login-page__divider-dot {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-color: #d9d9d9 !important;
|
||||
border-color: var(--border-color) !important;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
|
||||
<div class="product-detail__price-group">
|
||||
<span class="product-detail__price-current">
|
||||
{{ getFormattedPrice(prod.precio) }}
|
||||
{{ getFormattedPrice(effectivePrice()) }}
|
||||
</span>
|
||||
|
||||
@if (oldPrice(); as oldPrice) {
|
||||
@@ -99,7 +99,7 @@
|
||||
[class.product-detail__description-body--expanded]="descriptionExpanded()"
|
||||
[style.max-height.px]="descriptionExpanded() ? descriptionMaxHeight() || null : null"
|
||||
>
|
||||
{{ prod.descripcion }}
|
||||
{{ effectiveDescription() }}
|
||||
</div>
|
||||
|
||||
@if (showDescriptionToggle()) {
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
}
|
||||
|
||||
&__divider {
|
||||
border-top: 1px solid #e6e6e6;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
&__title {
|
||||
@@ -25,7 +25,7 @@
|
||||
}
|
||||
|
||||
&__title-price-divider {
|
||||
border-top: 1px solid #e6e6e6;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
&__price-group {
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
describe('ProductDetailPageComponent', () => {
|
||||
const mockProduct: CatalogItemDetail = {
|
||||
id: 1,
|
||||
type: 'product',
|
||||
category_id: 10,
|
||||
brand_id: null,
|
||||
slug: 'auriculares-bluetooth',
|
||||
@@ -327,6 +328,70 @@ describe('ProductDetailPageComponent', () => {
|
||||
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',
|
||||
sort_order: 0,
|
||||
metadata: null,
|
||||
},
|
||||
{
|
||||
id: 21,
|
||||
value: '21',
|
||||
label: '10/10/2026',
|
||||
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 () => {
|
||||
await configureTestingModule();
|
||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||
@@ -415,11 +480,13 @@ describe('ProductDetailPageComponent', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('tenant-test', {
|
||||
direct_item: {
|
||||
catalog_item_id: 1,
|
||||
variant_id: null,
|
||||
cantidad: 1,
|
||||
},
|
||||
direct_items: [
|
||||
{
|
||||
catalog_item_id: 1,
|
||||
variant_id: null,
|
||||
cantidad: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout'], {
|
||||
queryParams: { purchase: 44 },
|
||||
@@ -564,6 +631,39 @@ describe('ProductDetailPageComponent', () => {
|
||||
expect(fixture.componentInstance['quantity']()).toBe(2);
|
||||
});
|
||||
|
||||
it('caps an unlimited variant at the per-user purchase limit', async () => {
|
||||
const unlimitedVariant = {
|
||||
id: 322,
|
||||
stock_tecnico: null,
|
||||
values: {},
|
||||
};
|
||||
resolveProduct({
|
||||
...mockProduct,
|
||||
inventory_policy: 'unlimited',
|
||||
max_units_per_user: 2,
|
||||
selected_variant: {
|
||||
id: 322,
|
||||
stock_tecnico: null,
|
||||
images: [],
|
||||
values: { event_date: '20' },
|
||||
},
|
||||
variants: [unlimitedVariant],
|
||||
});
|
||||
|
||||
await configureTestingModule();
|
||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||
fixture.detectChanges();
|
||||
|
||||
const increaseButton = fixture.nativeElement.querySelector(
|
||||
'app-quantity-selector button:last-child',
|
||||
) as HTMLButtonElement;
|
||||
increaseButton.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.componentInstance['quantity']()).toBe(2);
|
||||
expect(increaseButton.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('disables purchase actions for tracked variants without stock', async () => {
|
||||
const trackedVariant = {
|
||||
id: 654,
|
||||
|
||||
@@ -86,13 +86,28 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
protected readonly creatingDirectPurchase = signal(false);
|
||||
protected readonly error = signal<string | null>(null);
|
||||
protected readonly selectedVariant = signal<CatalogItemVariant | null>(null);
|
||||
protected readonly effectiveDescription = computed(
|
||||
() => this.selectedVariant()?.descripcion ?? this.product()?.descripcion ?? '',
|
||||
);
|
||||
protected readonly effectivePrice = computed(
|
||||
() => this.selectedVariant()?.precio ?? this.product()?.precio,
|
||||
);
|
||||
protected readonly quantity = signal(1);
|
||||
protected readonly selectedVariantMax = computed<number | null>(() => {
|
||||
const prod = this.product();
|
||||
const variant = this.selectedVariant();
|
||||
if (variant) return variant.stock_tecnico;
|
||||
if (prod && prod.variants.length === 0) return prod.stock_tecnico ?? null;
|
||||
return 0;
|
||||
if (!prod) return 0;
|
||||
|
||||
const stockLimit = variant
|
||||
? variant.stock_tecnico
|
||||
: prod.variants.length === 0
|
||||
? (prod.stock_tecnico ?? null)
|
||||
: 0;
|
||||
const userLimit = prod.max_units_per_user ?? null;
|
||||
|
||||
if (stockLimit === null) return userLimit;
|
||||
if (userLimit === null) return stockLimit;
|
||||
return Math.min(stockLimit, userLimit);
|
||||
});
|
||||
protected readonly selectedVariantAvailable = computed(() => {
|
||||
const prod = this.product();
|
||||
@@ -100,6 +115,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
|
||||
const variant = this.selectedVariant();
|
||||
if (variant) return this.isVariantAvailable(variant, prod);
|
||||
if (prod.purpose === 'entry') return false;
|
||||
if (prod.variants.length > 0) return false;
|
||||
|
||||
return prod.inventory_policy === 'unlimited' || (prod.stock_tecnico ?? 0) > 0;
|
||||
@@ -108,7 +124,9 @@ 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.show_in_selector !== false && attribute.options.length > 0,
|
||||
),
|
||||
);
|
||||
protected readonly hasRenderableAttributes = computed(
|
||||
() => this.renderableAttributes().length > 0,
|
||||
@@ -123,6 +141,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
this.carouselHost();
|
||||
this.descriptionBody();
|
||||
this.product();
|
||||
this.selectedVariant();
|
||||
this.descriptionExpanded();
|
||||
|
||||
if (this.isBrowser) {
|
||||
@@ -159,26 +178,26 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
.withCustomLoading()
|
||||
.getCatalogItem(productId, variantId)
|
||||
.subscribe({
|
||||
next: (prod) => {
|
||||
this.applyProduct(prod, false);
|
||||
this.variantLoading.set(false);
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
const errorMessage = err.error?.message || 'No pudimos cargar la variante seleccionada.';
|
||||
this.toastService.danger(errorMessage);
|
||||
this.variantLoading.set(false);
|
||||
next: (prod) => {
|
||||
this.applyProduct(prod, false);
|
||||
this.variantLoading.set(false);
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
const errorMessage = err.error?.message || 'No pudimos cargar la variante seleccionada.';
|
||||
this.toastService.danger(errorMessage);
|
||||
this.variantLoading.set(false);
|
||||
|
||||
this.product.update((currentProduct) => {
|
||||
if (!currentProduct) return null;
|
||||
return {
|
||||
...currentProduct,
|
||||
variants: currentProduct.variants.filter((variant) => variant.id !== variantId),
|
||||
};
|
||||
});
|
||||
this.product.update((currentProduct) => {
|
||||
if (!currentProduct) return null;
|
||||
return {
|
||||
...currentProduct,
|
||||
variants: currentProduct.variants.filter((variant) => variant.id !== variantId),
|
||||
};
|
||||
});
|
||||
|
||||
this.attributeSelector()?.reset();
|
||||
},
|
||||
});
|
||||
this.attributeSelector()?.reset();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private applyResolvedData(resolvedData: ProductDetailResolvedData): void {
|
||||
@@ -230,8 +249,11 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
this.selectedVariant.set(variant);
|
||||
if (variant && variant.stock_tecnico !== null && this.quantity() > variant.stock_tecnico) {
|
||||
this.quantity.set(Math.max(1, variant.stock_tecnico));
|
||||
this.descriptionExpanded.set(false);
|
||||
this.descriptionHasOverflow.set(false);
|
||||
const maximum = this.selectedVariantMax();
|
||||
if (maximum !== null && this.quantity() > maximum) {
|
||||
this.quantity.set(Math.max(1, maximum));
|
||||
}
|
||||
|
||||
const currentProduct = this.product();
|
||||
@@ -253,17 +275,17 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
.withCustomLoading()
|
||||
.addItem(currentProduct.id, variant?.id ?? null, this.quantity())
|
||||
.subscribe({
|
||||
next: (res) => {
|
||||
const msg = res.message || 'Producto agregado al carrito';
|
||||
this.toastService.success(msg);
|
||||
this.addingToCart.set(false);
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
const errorMessage = err.error?.message || 'No se pudo agregar el producto al carrito.';
|
||||
this.toastService.danger(errorMessage);
|
||||
this.addingToCart.set(false);
|
||||
},
|
||||
});
|
||||
next: (res) => {
|
||||
const msg = res.message || 'Producto agregado al carrito';
|
||||
this.toastService.success(msg);
|
||||
this.addingToCart.set(false);
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
const errorMessage = err.error?.message || 'No se pudo agregar el producto al carrito.';
|
||||
this.toastService.danger(errorMessage);
|
||||
this.addingToCart.set(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected async buyNow(): Promise<void> {
|
||||
@@ -297,11 +319,13 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
this.creatingDirectPurchase.set(true);
|
||||
try {
|
||||
const purchase = await this.checkoutService.startCheckout(tenant.codigo, {
|
||||
direct_item: {
|
||||
catalog_item_id: currentProduct.id,
|
||||
variant_id: variant?.id ?? null,
|
||||
cantidad: this.quantity(),
|
||||
},
|
||||
direct_items: [
|
||||
{
|
||||
catalog_item_id: currentProduct.id,
|
||||
variant_id: variant?.id ?? null,
|
||||
cantidad: this.quantity(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await this.router.navigate(['/checkout'], {
|
||||
|
||||
@@ -159,11 +159,13 @@ export class SearchPageComponent {
|
||||
this.creatingDirectPurchase.set(true);
|
||||
try {
|
||||
const purchase = await this.injector.get(CheckoutService).startCheckout(tenant.codigo, {
|
||||
direct_item: {
|
||||
catalog_item_id: event.product.id,
|
||||
variant_id: event.variant ?? null,
|
||||
cantidad: event.quantity,
|
||||
},
|
||||
direct_items: [
|
||||
{
|
||||
catalog_item_id: event.product.id,
|
||||
variant_id: event.variant ?? null,
|
||||
cantidad: event.quantity,
|
||||
},
|
||||
],
|
||||
});
|
||||
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
@if (tenant()?.main_carousel_images; as mainCarouselImages) {
|
||||
@if (mainCarouselImages.length) {
|
||||
@if (mainCarouselImages(); as images) {
|
||||
@if (images.length) {
|
||||
<app-main-carousel
|
||||
class="store-home__main-carousel"
|
||||
[images]="mainCarouselImages"
|
||||
[images]="images"
|
||||
ariaLabel="Imágenes destacadas de la tienda"
|
||||
(firstImageReady)="mainCarouselReady.set(true)"
|
||||
/>
|
||||
}
|
||||
}
|
||||
|
||||
@if (tenant()?.hero_config || tenant()?.event_config) {
|
||||
<app-hero-banner
|
||||
[heroConfig]="tenant()?.hero_config"
|
||||
[eventConfig]="tenant()?.event_config"
|
||||
></app-hero-banner>
|
||||
@if (heroConfig() || eventConfig()) {
|
||||
<app-hero-banner [heroConfig]="heroConfig()" [eventConfig]="eventConfig()" />
|
||||
}
|
||||
|
||||
@if (error()) {
|
||||
@@ -33,6 +30,7 @@
|
||||
[items]="group.items"
|
||||
[loading]="isGroupLoading(group.id)"
|
||||
[loadImages]="!hasMainCarouselImages() || mainCarouselReady()"
|
||||
[unavailableVariantIds]="unavailableVariantIds()"
|
||||
(buy)="onBuyProduct($event)"
|
||||
(addToCart)="onAddToCart($event)"
|
||||
(pageChange)="onPageChange(group.id, $event)"
|
||||
@@ -40,3 +38,9 @@
|
||||
</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>
|
||||
}
|
||||
|
||||
@@ -11,6 +11,32 @@ app-store-section + app-store-section {
|
||||
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;
|
||||
}
|
||||
|
||||
@media (max-width: 767.98px) {
|
||||
:host > app-hero-banner:first-child {
|
||||
display: block;
|
||||
margin-top: -3rem;
|
||||
}
|
||||
}
|
||||
|
||||
.store-home__alert-error {
|
||||
margin: 0;
|
||||
border-color: rgba(var(--tenant-danger-rgb, 220, 53, 69), 0.18);
|
||||
|
||||
@@ -16,6 +16,7 @@ import { Tenant } from '../../../../core/services/tenant.interface';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
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 {
|
||||
STORE_HOME_PRODUCTS_ERROR_MESSAGE,
|
||||
@@ -88,7 +89,7 @@ const pageOneItems: CatalogFeaturedItem[] = [
|
||||
},
|
||||
];
|
||||
|
||||
function createTenant(mainCarouselImages?: string[]): Tenant {
|
||||
function createTenant(extras: Tenant['extras'] = {}): Tenant {
|
||||
return {
|
||||
id: 1,
|
||||
codigo: 'acme',
|
||||
@@ -102,8 +103,18 @@ function createTenant(mainCarouselImages?: string[]): Tenant {
|
||||
footer_bg_color: '#ffffff',
|
||||
header_logo: '/header.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: [],
|
||||
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 () => {
|
||||
const mainCarouselImages = [
|
||||
'https://example.com/carousel-1.webp',
|
||||
'https://example.com/carousel-2.webp',
|
||||
];
|
||||
it('renders the carousel URLs received in tenant extras', async () => {
|
||||
const carousel = ['https://example.com/carousel-1.webp', 'https://example.com/carousel-2.webp'];
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [StoreHomePageComponent],
|
||||
@@ -162,7 +170,7 @@ describe('StoreHomePageComponent', () => {
|
||||
},
|
||||
{
|
||||
provide: TenantService,
|
||||
useValue: createTenantServiceStub(createTenant(mainCarouselImages)),
|
||||
useValue: createTenantServiceStub(createTenant({ carousel })),
|
||||
},
|
||||
],
|
||||
}).compileComponents();
|
||||
@@ -171,25 +179,60 @@ describe('StoreHomePageComponent', () => {
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
const carousel = element.querySelector('app-main-carousel');
|
||||
const images = carousel?.querySelectorAll('.main-carousel__image');
|
||||
const carouselElement = element.querySelector('app-main-carousel');
|
||||
const images = carouselElement?.querySelectorAll('.main-carousel__image');
|
||||
|
||||
expect(element.firstElementChild).toBe(carousel);
|
||||
expect(element.firstElementChild).toBe(carouselElement);
|
||||
expect(images).toHaveLength(2);
|
||||
expect(images?.[0].getAttribute('src')).toBe(mainCarouselImages[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();
|
||||
expect(images?.[0].getAttribute('src')).toBe(carousel[0]);
|
||||
});
|
||||
|
||||
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.event_date_text = '5 y 6 de Diciembre 2026';
|
||||
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({
|
||||
imports: [StoreHomePageComponent],
|
||||
providers: [
|
||||
@@ -200,7 +243,7 @@ describe('StoreHomePageComponent', () => {
|
||||
},
|
||||
{
|
||||
provide: TenantService,
|
||||
useValue: createTenantServiceStub(createTenant([])),
|
||||
useValue: createTenantServiceStub(tenant),
|
||||
},
|
||||
],
|
||||
}).compileComponents();
|
||||
@@ -208,7 +251,127 @@ describe('StoreHomePageComponent', () => {
|
||||
const fixture = TestBed.createComponent(StoreHomePageComponent);
|
||||
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('5 y 6 de Diciembre 2026');
|
||||
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 () => {
|
||||
@@ -323,9 +486,9 @@ describe('StoreHomePageComponent', () => {
|
||||
it('adds a product-list cart event to the cart', async () => {
|
||||
const catalogServiceStub = { getCatalog: vi.fn(), getFeaturedGroupItems: vi.fn() };
|
||||
const cartServiceStub = {
|
||||
addItem: vi.fn().mockReturnValue(
|
||||
of({ data: {}, message: 'Producto agregado correctamente' }),
|
||||
),
|
||||
addItem: vi
|
||||
.fn()
|
||||
.mockReturnValue(of({ data: {}, message: 'Producto agregado correctamente' })),
|
||||
};
|
||||
const toastServiceStub = { success: vi.fn(), danger: vi.fn() };
|
||||
|
||||
|
||||
@@ -18,7 +18,10 @@ import { CatalogFeaturedGroup } from '../../../../core/services/catalog/catalog.
|
||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||
import {
|
||||
CheckoutService,
|
||||
isInsufficientStockResponse,
|
||||
} from '../../../../core/services/checkout.service';
|
||||
import {
|
||||
ProductListComponent,
|
||||
ProductListCartEvent,
|
||||
@@ -60,9 +63,36 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
protected readonly error = signal<string | null>(null);
|
||||
protected readonly mainCarouselReady = signal(false);
|
||||
protected readonly creatingDirectPurchase = signal(false);
|
||||
protected readonly hasMainCarouselImages = computed(
|
||||
() => (this.tenant()?.main_carousel_images?.length ?? 0) > 0,
|
||||
protected readonly unavailableVariantIds = signal<ReadonlySet<number>>(new Set<number>());
|
||||
protected readonly mainCarouselImages = computed(() => this.tenant()?.extras?.carousel ?? []);
|
||||
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_text: tenant.event_date_text,
|
||||
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 readonly groupRequestSubscriptions = new Map<number, Subscription>();
|
||||
@@ -109,20 +139,20 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
.withCustomLoading()
|
||||
.getFeaturedGroupItems(groupId, { page })
|
||||
.subscribe({
|
||||
next: (items) => {
|
||||
this.catalog.update((groups) =>
|
||||
groups.map((candidate) =>
|
||||
candidate.id === groupId ? { ...candidate, items } : candidate,
|
||||
),
|
||||
);
|
||||
this.error.set(null);
|
||||
},
|
||||
error: () => {
|
||||
this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE);
|
||||
this.setGroupLoading(groupId, false);
|
||||
},
|
||||
complete: () => this.setGroupLoading(groupId, false),
|
||||
});
|
||||
next: (items) => {
|
||||
this.catalog.update((groups) =>
|
||||
groups.map((candidate) =>
|
||||
candidate.id === groupId ? { ...candidate, items } : candidate,
|
||||
),
|
||||
);
|
||||
this.error.set(null);
|
||||
},
|
||||
error: () => {
|
||||
this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE);
|
||||
this.setGroupLoading(groupId, false);
|
||||
},
|
||||
complete: () => this.setGroupLoading(groupId, false),
|
||||
});
|
||||
|
||||
this.groupRequestSubscriptions.set(groupId, subscription);
|
||||
}
|
||||
@@ -152,16 +182,39 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
|
||||
this.creatingDirectPurchase.set(true);
|
||||
try {
|
||||
const purchase = await this.injector.get(CheckoutService).startCheckout(tenant.codigo, {
|
||||
direct_item: {
|
||||
catalog_item_id: event.product.id,
|
||||
variant_id: event.variant ?? null,
|
||||
cantidad: event.quantity,
|
||||
},
|
||||
const checkoutService = this.injector.get(CheckoutService);
|
||||
const variantIds = event.variantIds ?? [];
|
||||
const directItems =
|
||||
variantIds.length > 0
|
||||
? variantIds.map((variantId) => ({
|
||||
catalog_item_id: event.product.id,
|
||||
variant_id: variantId,
|
||||
cantidad: 1,
|
||||
}))
|
||||
: [
|
||||
{
|
||||
catalog_item_id: event.product.id,
|
||||
variant_id: event.variant ?? null,
|
||||
cantidad: event.quantity,
|
||||
},
|
||||
];
|
||||
const purchase = await checkoutService.startCheckout(tenant.codigo, {
|
||||
direct_items: directItems,
|
||||
});
|
||||
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
||||
} catch (error) {
|
||||
console.error('Failed to create direct purchase:', error);
|
||||
|
||||
if (error instanceof HttpErrorResponse && isInsufficientStockResponse(error.error)) {
|
||||
const unavailableIds = error.error.unavailable_items
|
||||
.map((item) => item.variant_id)
|
||||
.filter((variantId): variantId is number => variantId !== null);
|
||||
|
||||
this.unavailableVariantIds.update((current) => new Set([...current, ...unavailableIds]));
|
||||
this.toastService.danger(error.error.message);
|
||||
return;
|
||||
}
|
||||
|
||||
this.toastService.danger('No se pudo iniciar la compra directa.');
|
||||
} finally {
|
||||
this.creatingDirectPurchase.set(false);
|
||||
@@ -189,14 +242,14 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
.withCustomLoading()
|
||||
.getCatalog()
|
||||
.subscribe({
|
||||
next: (catalog) => this.catalog.set(catalog),
|
||||
error: () => {
|
||||
this.catalog.set([]);
|
||||
this.loading.set(false);
|
||||
this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE);
|
||||
},
|
||||
complete: () => this.loading.set(false),
|
||||
});
|
||||
next: (catalog) => this.catalog.set(catalog),
|
||||
error: () => {
|
||||
this.catalog.set([]);
|
||||
this.loading.set(false);
|
||||
this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE);
|
||||
},
|
||||
complete: () => this.loading.set(false),
|
||||
});
|
||||
}
|
||||
|
||||
private applyResolvedData(resolvedData: StoreHomeCatalogResolvedData): void {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
}
|
||||
|
||||
.accordion {
|
||||
--bs-accordion-border-color: #dedede;
|
||||
--bs-accordion-border-color: var(--border-color);
|
||||
--bs-accordion-border-radius: 0;
|
||||
--bs-accordion-inner-border-radius: 0;
|
||||
--bs-accordion-bg: transparent;
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
<article
|
||||
class="w-100 p-3 rounded-0 cart-item"
|
||||
[class.cart-item-with-media]="imageUrl()"
|
||||
>
|
||||
<article class="w-100 p-3 rounded-0 cart-item" [class.cart-item-with-media]="imageUrl()">
|
||||
@if (imageUrl()) {
|
||||
<div class="position-relative overflow-hidden cart-item-media">
|
||||
@if (discountPercentage() && discountPercentage()! > 0) {
|
||||
<span class="position-absolute top-0 start-0 z-1 rounded-0 cart-item-discount-badge">-{{ discountPercentage() }}%</span>
|
||||
<span class="position-absolute top-0 start-0 z-1 rounded-0 cart-item-discount-badge"
|
||||
>-{{ discountPercentage() }}%</span
|
||||
>
|
||||
}
|
||||
|
||||
<img class="w-100 h-100 object-fit-cover d-block" [src]="imageUrl()" [alt]="product()" />
|
||||
@@ -18,21 +17,33 @@
|
||||
|
||||
<div class="text-nowrap cart-item-prices">
|
||||
@if (formattedOriginalPrice(); as originalPrice) {
|
||||
<span class="text-decoration-line-through mb-1 fw-light cart-item-original-price">{{ originalPrice }}</span>
|
||||
<span class="text-decoration-line-through mb-1 fw-light cart-item-original-price">{{
|
||||
originalPrice
|
||||
}}</span>
|
||||
}
|
||||
|
||||
<span class="fw-bold cart-item-discounted-price">{{ formattedDiscountedPrice() }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-grid cart-item-attributes">
|
||||
@for (attribute of attributes(); track attribute.label + attribute.value) {
|
||||
<div class="cart-item-attribute">
|
||||
<span class="fw-normal cart-item-attribute-label">{{ attribute.label }}: </span>
|
||||
<span class="fw-bold">{{ attribute.value }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
@if (hasVariantSelectors() && !quantityDisabled()) {
|
||||
<app-variant-selector
|
||||
class="cart-item-variant-selector"
|
||||
[variants]="variants()"
|
||||
[selectedVariant]="selectedVariant()"
|
||||
[compact]="true"
|
||||
(selectedVariantChange)="onVariantChange($event)"
|
||||
/>
|
||||
} @else {
|
||||
<div class="d-grid cart-item-attributes">
|
||||
@for (attribute of attributes(); track attribute.label + attribute.value) {
|
||||
<div class="cart-item-attribute">
|
||||
<span class="fw-normal cart-item-attribute-label">{{ attribute.label }}: </span>
|
||||
<span class="fw-bold">{{ attribute.value }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!readonly()) {
|
||||
<div class="d-flex justify-content-end align-items-center mt-auto cart-item-actions">
|
||||
@@ -45,15 +56,9 @@
|
||||
(decrease)="onDecrease()"
|
||||
/>
|
||||
@if (!quantityDisabled() && showRemove()) {
|
||||
<app-icon-button
|
||||
variant="trash"
|
||||
class="cart-item-remove-btn"
|
||||
(click)="onRemove()"
|
||||
/>
|
||||
<app-icon-button variant="trash" class="cart-item-remove-btn" (click)="onRemove()" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</article>
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
:host(:first-child) .cart-item::before,
|
||||
:host .cart-item::after {
|
||||
content: "";
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: var(--item-divider-inset);
|
||||
left: var(--item-divider-inset);
|
||||
@@ -43,7 +43,7 @@
|
||||
aspect-ratio: 1 / 1;
|
||||
border-radius: 5px 0 0 5px;
|
||||
background-color: #ffffff;
|
||||
border: 1px solid #eaeaea;
|
||||
border: 1px solid var(--border-color);
|
||||
overflow: hidden;
|
||||
|
||||
img {
|
||||
@@ -119,6 +119,11 @@
|
||||
gap: 0.125rem;
|
||||
}
|
||||
|
||||
.cart-item-variant-selector {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.cart-item-remove-btn {
|
||||
margin-left: 0.35rem;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
|
||||
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
||||
import { IconButtonComponent } from '../icon-button/icon-button.component';
|
||||
import {
|
||||
VariantSelectorComponent,
|
||||
VariantSelectorVariant,
|
||||
} from '../variant-selector/variant-selector.component';
|
||||
|
||||
export interface CartItemAttribute {
|
||||
label: string;
|
||||
@@ -10,10 +14,10 @@ export interface CartItemAttribute {
|
||||
@Component({
|
||||
selector: 'app-cart-item',
|
||||
standalone: true,
|
||||
imports: [QuantitySelectorComponent, IconButtonComponent],
|
||||
imports: [QuantitySelectorComponent, IconButtonComponent, VariantSelectorComponent],
|
||||
templateUrl: './cart-item.component.html',
|
||||
styleUrl: './cart-item.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class CartItemComponent {
|
||||
readonly imageUrl = input<string | null>(null);
|
||||
@@ -22,6 +26,8 @@ export class CartItemComponent {
|
||||
readonly discountedPrice = input<number>(0);
|
||||
readonly discountPercentage = input<number | null>(null);
|
||||
readonly attributes = input<CartItemAttribute[]>([]);
|
||||
readonly variants = input<VariantSelectorVariant[]>([]);
|
||||
readonly selectedVariant = input<unknown>(null);
|
||||
readonly quantity = input<number>(1);
|
||||
readonly readonly = input<boolean>(false);
|
||||
readonly quantityDisabled = input<boolean>(false);
|
||||
@@ -31,6 +37,11 @@ export class CartItemComponent {
|
||||
readonly remove = output<void>();
|
||||
readonly increase = output<void>();
|
||||
readonly decrease = output<void>();
|
||||
readonly variantChange = output<number>();
|
||||
|
||||
protected readonly hasVariantSelectors = computed(() =>
|
||||
this.variants().some((variant) => Object.keys(variant.values).length > 0),
|
||||
);
|
||||
|
||||
protected onQuantityChange(newQuantity: number): void {
|
||||
if (this.quantityDisabled()) return;
|
||||
@@ -49,12 +60,20 @@ export class CartItemComponent {
|
||||
this.decrease.emit();
|
||||
}
|
||||
|
||||
protected onVariantChange(variant: unknown): void {
|
||||
if (!this.quantityDisabled() && typeof variant === 'number') {
|
||||
this.variantChange.emit(variant);
|
||||
}
|
||||
}
|
||||
|
||||
protected readonly formattedOriginalPrice = computed(() => {
|
||||
const price = this.originalPrice();
|
||||
return price === null ? null : this.formatCurrency(price);
|
||||
});
|
||||
|
||||
protected readonly formattedDiscountedPrice = computed(() => this.formatCurrency(this.discountedPrice()));
|
||||
protected readonly formattedDiscountedPrice = computed(() =>
|
||||
this.formatCurrency(this.discountedPrice()),
|
||||
);
|
||||
|
||||
private formatCurrency(value: number): string {
|
||||
const rounded = Math.round(value);
|
||||
|
||||
@@ -44,11 +44,14 @@
|
||||
[discountedPrice]="item.discountedPrice"
|
||||
[discountPercentage]="item.discountPercentage"
|
||||
[attributes]="item.attributes"
|
||||
[variants]="item.variants ?? []"
|
||||
[selectedVariant]="getItemVariant(item)"
|
||||
[quantity]="getItemQuantity(item)"
|
||||
[readonly]="readonly()"
|
||||
[quantityDisabled]="editingDisabled() || (allowEditing() && !editing())"
|
||||
[showRemove]="allowRemove()"
|
||||
(quantityChange)="onItemQuantityChange(idx, $event)"
|
||||
(variantChange)="onItemVariantChange(idx, $event)"
|
||||
(remove)="onItemRemove(idx)"
|
||||
/>
|
||||
} @empty {
|
||||
|
||||
@@ -115,7 +115,7 @@ describe('CartComponent', () => {
|
||||
|
||||
expect(openConfirmDelete).toHaveBeenCalledWith({
|
||||
title: 'Eliminar producto',
|
||||
content: 'Se eliminara "Producto de prueba" del carrito. Esta accion no se puede deshacer.',
|
||||
content: 'Se eliminará “Producto de prueba” del carrito. Esta acción no se puede deshacer.',
|
||||
confirmLabel: 'Eliminar',
|
||||
cancelLabel: 'Cancelar',
|
||||
});
|
||||
@@ -407,4 +407,57 @@ describe('CartComponent', () => {
|
||||
fixture.debugElement.query(By.css('app-cart-item')).componentInstance.quantityDisabled(),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('persists a variant selected from a cart row', async () => {
|
||||
const updateItemVariant = vi.fn().mockReturnValue(
|
||||
of({
|
||||
message: 'Variante actualizada.',
|
||||
data: {},
|
||||
}),
|
||||
);
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CartComponent],
|
||||
providers: [
|
||||
{
|
||||
provide: CartService,
|
||||
useValue: {
|
||||
cart: signal(null).asReadonly(),
|
||||
updateItemQuantity: vi.fn(),
|
||||
updateItemVariant,
|
||||
removeItem: vi.fn(),
|
||||
},
|
||||
},
|
||||
{ provide: ModalService, useValue: {} },
|
||||
{
|
||||
provide: ToastService,
|
||||
useValue: { success: vi.fn(), info: vi.fn(), danger: vi.fn() },
|
||||
},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(CartComponent);
|
||||
fixture.componentRef.setInput('items', [
|
||||
{
|
||||
cartItemId: 10,
|
||||
imageUrl: null,
|
||||
product: 'Comida',
|
||||
originalPrice: null,
|
||||
discountedPrice: 1000,
|
||||
discountPercentage: null,
|
||||
attributes: [{ label: 'Servicio', value: 'Almuerzo' }],
|
||||
quantity: 2,
|
||||
variantId: 20,
|
||||
variants: [
|
||||
{ id: 20, values: { servicio: 'Almuerzo' } },
|
||||
{ id: 21, values: { servicio: 'Cena' } },
|
||||
],
|
||||
},
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
fixture.debugElement.query(By.css('app-cart-item')).triggerEventHandler('variantChange', 21);
|
||||
|
||||
expect(updateItemVariant).toHaveBeenCalledWith(10, 2, 21);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -16,6 +16,7 @@ import { CartItemAttribute, CartItemComponent } from '../cart-item/cart-item.com
|
||||
import { ModalService } from '../../../core/services/modal.service';
|
||||
import { CartService } from '../../../core/services/cart/cart.service';
|
||||
import { ToastService } from '../../../core/services/toast.service';
|
||||
import { VariantSelectorVariant } from '../variant-selector/variant-selector.component';
|
||||
|
||||
export interface CartItemMock {
|
||||
cartItemId?: number;
|
||||
@@ -26,6 +27,8 @@ export interface CartItemMock {
|
||||
discountPercentage: number | null;
|
||||
attributes: CartItemAttribute[];
|
||||
quantity: number;
|
||||
variantId?: number | null;
|
||||
variants?: VariantSelectorVariant[];
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -64,6 +67,7 @@ export class CartComponent {
|
||||
}>();
|
||||
|
||||
protected readonly quantityOverrides = signal<Record<number, number>>({});
|
||||
protected readonly variantOverrides = signal<Record<number, number>>({});
|
||||
constructor() {
|
||||
this.quantityUpdates$
|
||||
.pipe(
|
||||
@@ -104,6 +108,13 @@ export class CartComponent {
|
||||
return item.quantity;
|
||||
}
|
||||
|
||||
protected getItemVariant(item: CartItemMock): number | null {
|
||||
if (item.cartItemId !== undefined && this.variantOverrides()[item.cartItemId] !== undefined) {
|
||||
return this.variantOverrides()[item.cartItemId];
|
||||
}
|
||||
return item.variantId ?? null;
|
||||
}
|
||||
|
||||
private clearOverride(cartItemId: number): void {
|
||||
this.quantityOverrides.update((overrides) => {
|
||||
const copy = { ...overrides };
|
||||
@@ -153,6 +164,36 @@ export class CartComponent {
|
||||
}
|
||||
}
|
||||
|
||||
protected onItemVariantChange(index: number, variantId: number): void {
|
||||
const item = this.items()[index];
|
||||
const cartItemId = item?.cartItemId;
|
||||
|
||||
if (!item || !cartItemId || variantId === this.getItemVariant(item)) return;
|
||||
|
||||
this.variantOverrides.update((overrides) => ({ ...overrides, [cartItemId]: variantId }));
|
||||
this.cartService
|
||||
.updateItemVariant(cartItemId, this.getItemQuantity(item), variantId)
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
this.clearVariantOverride(cartItemId);
|
||||
this.toastService.success(response.message || 'Variante actualizada.');
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
console.error('Error updating cart item variant', error);
|
||||
this.clearVariantOverride(cartItemId);
|
||||
this.toastService.danger(error.error?.message || 'No se pudo actualizar la variante.');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private clearVariantOverride(cartItemId: number): void {
|
||||
this.variantOverrides.update((overrides) => {
|
||||
const copy = { ...overrides };
|
||||
delete copy[cartItemId];
|
||||
return copy;
|
||||
});
|
||||
}
|
||||
|
||||
protected onItemRemove(index: number): void {
|
||||
const target = this.resolveRemoveTarget(index);
|
||||
|
||||
@@ -163,7 +204,7 @@ export class CartComponent {
|
||||
this.modalService
|
||||
.openConfirmDelete({
|
||||
title: 'Eliminar producto',
|
||||
content: `Se eliminara "${target.productName}" del carrito. Esta accion no se puede deshacer.`,
|
||||
content: `Se eliminará “${target.productName}” del carrito. Esta acción no se puede deshacer.`,
|
||||
confirmLabel: 'Eliminar',
|
||||
cancelLabel: 'Cancelar',
|
||||
})
|
||||
|
||||
@@ -1,19 +1,25 @@
|
||||
.confirm-modal {
|
||||
display: grid;
|
||||
gap: 1.5rem;
|
||||
justify-items: center;
|
||||
width: 100%;
|
||||
gap: 1.25rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.confirm-modal__content {
|
||||
margin: 0;
|
||||
color: #666666;
|
||||
line-height: 1.5;
|
||||
color: #5f6368;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.confirm-modal__actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
width: 100%;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
@media (max-width: 380px) {
|
||||
.confirm-modal__actions {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
.global-loading__spinner {
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
border: 0.25rem solid rgba(32, 32, 32, 0.12);
|
||||
border: 0.25rem solid var(--border-color);
|
||||
border-top-color: var(--tenant-primary, #6376f3);
|
||||
border-radius: 50%;
|
||||
animation: global-loading-spin 0.75s linear infinite;
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
<div class="hero-banner-container">
|
||||
<div
|
||||
class="hero-banner position-relative rounded"
|
||||
>
|
||||
<div class="hero-banner position-relative rounded">
|
||||
<div
|
||||
class="hero-media"
|
||||
aria-hidden="true"
|
||||
[ngStyle]="{'background-image': heroConfig?.background_image ? 'url(' + heroConfig.background_image + ')' : 'none'}"
|
||||
[ngStyle]="{
|
||||
'background-image': heroConfig?.background_image_id
|
||||
? 'url(' + heroConfig.background_image_id + ')'
|
||||
: 'none',
|
||||
}"
|
||||
></div>
|
||||
|
||||
|
||||
@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">
|
||||
@if (heroConfig.title_html) {
|
||||
<div class="hero-title" [innerHTML]="heroConfig.title_html"></div>
|
||||
@@ -18,7 +22,10 @@
|
||||
<div class="hero-description" [innerHTML]="heroConfig.description_html"></div>
|
||||
}
|
||||
@if (heroConfig.button_text) {
|
||||
<a [href]="heroConfig.button_href || '#'" class="hero-action text-decoration-none mt-3 d-inline-block">
|
||||
<a
|
||||
[href]="heroConfig.button_href || '#'"
|
||||
class="hero-action text-decoration-none mt-3 d-inline-block"
|
||||
>
|
||||
<app-button variant="primary">
|
||||
{{ heroConfig.button_text }}
|
||||
</app-button>
|
||||
@@ -27,35 +34,78 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (eventConfig) {
|
||||
<div class="event-card-container position-absolute w-100 d-flex justify-content-center">
|
||||
<div id="event-details" class="event-card bg-white shadow rounded p-3 p-md-4 text-center">
|
||||
@if (eventConfig.title) {
|
||||
<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">
|
||||
@if (eventConfig.dates && eventConfig.dates.length > 0) {
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<i class="fa-regular fa-calendar event-icon"></i>
|
||||
<span class="event-info-text">{{ formattedDates }}</span>
|
||||
</div>
|
||||
}
|
||||
@if (eventConfig.location) {
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<i class="fa-solid fa-location-dot event-icon"></i>
|
||||
<span class="event-info-text">{{ eventConfig.location }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="event-schedule-label" aria-hidden="true">
|
||||
<i class="fa-solid fa-chevron-down"></i>
|
||||
<span>Ver horarios</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (eventConfig) {
|
||||
<div class="event-card-container w-100 d-flex justify-content-center">
|
||||
<div id="event-details" class="event-card bg-white shadow rounded p-3 p-md-4 text-center">
|
||||
@if (eventConfig.title) {
|
||||
<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"
|
||||
>
|
||||
@if (eventConfig.dates && eventConfig.dates.length > 0) {
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<i class="fa-regular fa-calendar event-icon"></i>
|
||||
<span class="event-info-text">{{ formattedDates }}</span>
|
||||
</div>
|
||||
}
|
||||
@if (eventConfig.location) {
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<i class="fa-solid fa-location-dot event-icon"></i>
|
||||
<span class="event-info-text">{{ eventConfig.location }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (eventConfig.dates && eventConfig.dates.length > 0) {
|
||||
<button
|
||||
type="button"
|
||||
class="event-schedule-toggle"
|
||||
[attr.aria-expanded]="schedulesExpanded"
|
||||
aria-controls="event-schedules"
|
||||
(click)="toggleSchedules()"
|
||||
>
|
||||
<i
|
||||
class="fa-solid"
|
||||
[class.fa-chevron-down]="!schedulesExpanded"
|
||||
[class.fa-chevron-up]="schedulesExpanded"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span>{{ schedulesExpanded ? 'Ocultar horarios' : 'Ver horarios' }}</span>
|
||||
</button>
|
||||
|
||||
@if (schedulesExpanded) {
|
||||
<div id="event-schedules" class="event-schedules">
|
||||
<table class="table table-striped table-borderless mb-0">
|
||||
<tbody>
|
||||
@for (eventDate of eventConfig.dates; track eventDate.id ?? eventDate.date) {
|
||||
<tr>
|
||||
<td>
|
||||
<span class="event-schedule-value">
|
||||
<i class="fa-regular fa-calendar" aria-hidden="true"></i>
|
||||
<span>{{ formatScheduleDate(eventDate.date) }}</span>
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<span class="event-schedule-value">
|
||||
<i class="fa-regular fa-clock" aria-hidden="true"></i>
|
||||
<span>
|
||||
{{ formatScheduleTime(eventDate.start_time) }} -
|
||||
{{ formatScheduleTime(eventDate.end_time) }}
|
||||
</span>
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
.hero-banner-container {
|
||||
padding-bottom: 4rem; /* Spacing to accommodate the overlapping card */
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
@@ -19,10 +18,15 @@
|
||||
border-radius: inherit;
|
||||
|
||||
&::after {
|
||||
content: "";
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 0.95) 100%);
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
rgba(255, 255, 255, 0) 0%,
|
||||
rgba(255, 255, 255, 0.7) 50%,
|
||||
rgba(255, 255, 255, 0.95) 100%
|
||||
);
|
||||
border-radius: inherit;
|
||||
}
|
||||
}
|
||||
@@ -39,8 +43,8 @@
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
|
||||
::ng-deep .hero-title, .hero-title {
|
||||
::ng-deep .hero-title,
|
||||
.hero-title {
|
||||
color: #666666;
|
||||
font-size: 1.5rem;
|
||||
margin-bottom: 1rem;
|
||||
@@ -49,7 +53,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .hero-description, .hero-description {
|
||||
::ng-deep .hero-title h1 {
|
||||
margin: 0;
|
||||
color: inherit;
|
||||
font-size: inherit;
|
||||
font-weight: 700;
|
||||
line-height: inherit;
|
||||
}
|
||||
|
||||
::ng-deep .hero-description,
|
||||
.hero-description {
|
||||
color: #666666;
|
||||
font-size: 1.1rem;
|
||||
line-height: 1.5;
|
||||
@@ -59,8 +72,8 @@
|
||||
}
|
||||
|
||||
.event-card-container {
|
||||
bottom: -40px; /* Negative margin to pull it down and overlap */
|
||||
left: 0;
|
||||
position: relative;
|
||||
margin-top: -40px;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
@@ -70,12 +83,14 @@
|
||||
}
|
||||
|
||||
.event-title {
|
||||
font-size: 1.4rem;
|
||||
font-size: 25px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.5px;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.event-details {
|
||||
font-size: 1.1rem;
|
||||
font-size: 21px;
|
||||
}
|
||||
|
||||
.event-icon {
|
||||
@@ -85,11 +100,54 @@
|
||||
|
||||
.event-info-text {
|
||||
color: #8a8a8a;
|
||||
font-weight: 500;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.event-schedule-label {
|
||||
display: none;
|
||||
.event-schedule-toggle {
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
margin-top: 1.75rem;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--tenant-primary, #009d4f);
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid currentColor;
|
||||
outline-offset: 0.25rem;
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
}
|
||||
|
||||
.event-schedules {
|
||||
margin-top: 1.25rem;
|
||||
|
||||
td {
|
||||
width: 50%;
|
||||
padding: 0.65rem 1rem;
|
||||
vertical-align: middle;
|
||||
}
|
||||
}
|
||||
|
||||
.event-schedule-value {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
color: #8a8a8a;
|
||||
font-size: 19px;
|
||||
font-weight: 400;
|
||||
|
||||
i {
|
||||
width: 1rem;
|
||||
color: #c9ccce;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767.98px) {
|
||||
@@ -99,9 +157,12 @@
|
||||
}
|
||||
|
||||
.hero-banner {
|
||||
width: 100vw;
|
||||
min-height: 0;
|
||||
margin-inline: calc(50% - 50vw);
|
||||
overflow: hidden;
|
||||
background-color: #f5f5f5;
|
||||
border-radius: 0 !important;
|
||||
}
|
||||
|
||||
.hero-media {
|
||||
@@ -109,7 +170,7 @@
|
||||
inset: auto;
|
||||
flex: 0 0 auto;
|
||||
width: 100%;
|
||||
height: clamp(8.75rem, 44vw, 10.5rem);
|
||||
height: clamp(8.75rem, 44vw, 211px);
|
||||
background-position: center center;
|
||||
background-size: 140% auto;
|
||||
border-radius: 0;
|
||||
@@ -168,39 +229,33 @@
|
||||
}
|
||||
|
||||
.hero-action ::ng-deep .btn {
|
||||
min-height: 1.875rem;
|
||||
padding: 0.4rem 1.35rem;
|
||||
border-radius: 0.25rem;
|
||||
font-size: 0.625rem;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.event-card-container {
|
||||
position: relative !important;
|
||||
bottom: auto;
|
||||
left: auto;
|
||||
padding: 0 1.25rem 1.2rem;
|
||||
margin-top: 0;
|
||||
padding: 0 0 1.2rem;
|
||||
}
|
||||
|
||||
.event-card {
|
||||
width: 100%;
|
||||
max-width: 22rem;
|
||||
max-width: none;
|
||||
min-height: 11.4rem;
|
||||
padding: 1.75rem 1rem 0.8rem !important;
|
||||
padding: 2.5rem 1.5rem !important;
|
||||
border-radius: 0 !important;
|
||||
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.04) !important;
|
||||
}
|
||||
|
||||
.event-title {
|
||||
max-width: 16rem;
|
||||
margin: 0 auto 0.85rem !important;
|
||||
font-size: 1rem;
|
||||
font-size: 22px;
|
||||
line-height: 1.1;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.event-details {
|
||||
gap: 0.45rem !important;
|
||||
font-size: 0.7rem;
|
||||
font-size: 15px;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
@@ -213,22 +268,25 @@
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.event-info-text {
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.event-schedule-label {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
.event-schedule-toggle {
|
||||
margin-top: 1.9rem;
|
||||
color: var(--tenant-primary, #009d4f);
|
||||
font-size: 0.625rem;
|
||||
font-weight: 700;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.event-schedule-label i {
|
||||
.event-schedule-toggle i {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
|
||||
.event-schedules {
|
||||
margin-top: 1rem;
|
||||
|
||||
td {
|
||||
padding: 0.55rem 0.4rem;
|
||||
}
|
||||
}
|
||||
|
||||
.event-schedule-value {
|
||||
gap: 0.4rem;
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { HeroBannerComponent } from './hero-banner.component';
|
||||
|
||||
describe('HeroBannerComponent', () => {
|
||||
it('expands and collapses the event schedules', async () => {
|
||||
await TestBed.configureTestingModule({ imports: [HeroBannerComponent] }).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(HeroBannerComponent);
|
||||
fixture.componentRef.setInput('eventConfig', {
|
||||
title: 'Fiesta Nacional del Fútbol Infantil',
|
||||
location: 'Sunchales, Santa Fe',
|
||||
dates: [
|
||||
{
|
||||
id: 1,
|
||||
date: '2026-10-09',
|
||||
start_time: '10:00:00',
|
||||
end_time: '20:30:00',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
date: '2026-10-10',
|
||||
start_time: '10:00:00',
|
||||
end_time: '22:00:00',
|
||||
},
|
||||
],
|
||||
});
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
const toggle = element.querySelector<HTMLButtonElement>('.event-schedule-toggle');
|
||||
|
||||
expect(toggle?.textContent).toContain('Ver horarios');
|
||||
expect(toggle?.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(element.querySelector('.event-schedules')).toBeNull();
|
||||
|
||||
toggle?.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(toggle?.textContent).toContain('Ocultar horarios');
|
||||
expect(toggle?.getAttribute('aria-expanded')).toBe('true');
|
||||
expect(element.querySelectorAll('.event-schedules tbody tr')).toHaveLength(2);
|
||||
expect(element.querySelector('.event-schedules')?.textContent).toContain('9 de Octubre 2026');
|
||||
expect(element.querySelector('.event-schedules')?.textContent).toContain('10:00 - 20:30');
|
||||
|
||||
toggle?.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(element.querySelector('.event-schedules')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Component, ChangeDetectionStrategy, Input } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
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';
|
||||
|
||||
@Component({
|
||||
@@ -16,26 +16,41 @@ export class HeroBannerComponent {
|
||||
@Input() heroConfig?: HeroConfig | null;
|
||||
@Input() eventConfig?: EventConfig | null;
|
||||
|
||||
protected schedulesExpanded = false;
|
||||
|
||||
get formattedDates(): string {
|
||||
if (this.eventConfig?.dates_text) {
|
||||
return this.eventConfig.dates_text;
|
||||
}
|
||||
|
||||
if (!this.eventConfig?.dates || this.eventConfig.dates.length === 0) {
|
||||
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.map(({ date }) => date).join(', ');
|
||||
}
|
||||
|
||||
protected toggleSchedules(): void {
|
||||
this.schedulesExpanded = !this.schedulesExpanded;
|
||||
}
|
||||
|
||||
protected formatScheduleDate(date: string): string {
|
||||
const [year, month, day] = date.split('-').map(Number);
|
||||
|
||||
if (!year || !month || !day) {
|
||||
return date;
|
||||
}
|
||||
|
||||
return this.eventConfig.dates.join(', ');
|
||||
const monthName = new Intl.DateTimeFormat('es-AR', {
|
||||
month: 'long',
|
||||
timeZone: 'UTC',
|
||||
}).format(new Date(Date.UTC(year, month - 1, day)));
|
||||
const capitalizedMonth = `${monthName.charAt(0).toUpperCase()}${monthName.slice(1)}`;
|
||||
|
||||
return `${day} de ${capitalizedMonth} ${year}`;
|
||||
}
|
||||
|
||||
protected formatScheduleTime(time: string): string {
|
||||
return time.match(/^\d{2}:\d{2}/)?.[0] ?? time;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
min-height: 40px;
|
||||
padding: 0.625rem 1rem;
|
||||
border-radius: 5px;
|
||||
border-color: #cccccc;
|
||||
border-color: var(--border-color);
|
||||
color: #666666;
|
||||
font-size: 15px;
|
||||
font-weight: 400;
|
||||
|
||||
@@ -3,25 +3,10 @@ import { Component, inject } from '@angular/core';
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import {
|
||||
BrowserTestingModule,
|
||||
platformBrowserTesting
|
||||
} from '@angular/platform-browser/testing';
|
||||
import {
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi
|
||||
} from 'vitest';
|
||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
MODAL_DATA,
|
||||
ModalRef,
|
||||
ModalService
|
||||
} from '../../../core/services/modal.service';
|
||||
import { MODAL_DATA, ModalRef, ModalService } from '../../../core/services/modal.service';
|
||||
import { ModalHostComponent } from './modal-host.component';
|
||||
|
||||
@Component({
|
||||
@@ -31,7 +16,7 @@ import { ModalHostComponent } from './modal-host.component';
|
||||
<span class="modal-test-title">{{ data?.title }}</span>
|
||||
<button type="button" class="modal-test-close" (click)="close()">Cerrar</button>
|
||||
</div>
|
||||
`
|
||||
`,
|
||||
})
|
||||
class ModalContentTestComponent {
|
||||
readonly data = inject<{ title: string } | null>(MODAL_DATA);
|
||||
@@ -48,10 +33,7 @@ describe('ModalHostComponent', () => {
|
||||
|
||||
beforeAll(() => {
|
||||
try {
|
||||
getTestBed().initTestEnvironment(
|
||||
BrowserTestingModule,
|
||||
platformBrowserTesting()
|
||||
);
|
||||
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
|
||||
} catch {
|
||||
// Test environment may already be initialized by another setup entrypoint.
|
||||
}
|
||||
@@ -59,7 +41,7 @@ describe('ModalHostComponent', () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [ModalHostComponent]
|
||||
imports: [ModalHostComponent],
|
||||
}).compileComponents();
|
||||
|
||||
service = TestBed.inject(ModalService);
|
||||
@@ -68,6 +50,7 @@ describe('ModalHostComponent', () => {
|
||||
|
||||
afterEach(() => {
|
||||
doc.body.style.overflow = '';
|
||||
doc.body.style.paddingRight = '';
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
@@ -84,7 +67,7 @@ describe('ModalHostComponent', () => {
|
||||
|
||||
service.open(ModalContentTestComponent, {
|
||||
title: 'Editar producto',
|
||||
data: { title: 'Contenido del modal' }
|
||||
data: { title: 'Contenido del modal' },
|
||||
});
|
||||
fixture.detectChanges();
|
||||
|
||||
@@ -99,27 +82,30 @@ describe('ModalHostComponent', () => {
|
||||
it('closes with a result from the child component', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
data: { title: 'Cerrar' }
|
||||
data: { title: 'Cerrar' },
|
||||
});
|
||||
const closedSpy = vi.fn();
|
||||
|
||||
ref.afterClosed$.subscribe(closedSpy);
|
||||
fixture.detectChanges();
|
||||
|
||||
const closeButton = fixture.nativeElement.querySelector('.modal-test-close') as HTMLButtonElement;
|
||||
const closeButton = fixture.nativeElement.querySelector(
|
||||
'.modal-test-close',
|
||||
) as HTMLButtonElement;
|
||||
closeButton.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(closedSpy).toHaveBeenCalledWith('accepted');
|
||||
expect(service.activeModal()).toBeNull();
|
||||
expect(doc.body.style.overflow).toBe('');
|
||||
expect(doc.body.style.paddingRight).toBe('');
|
||||
});
|
||||
|
||||
it('closes on backdrop click when enabled', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
data: { title: 'Backdrop' },
|
||||
closeOnBackdrop: true
|
||||
closeOnBackdrop: true,
|
||||
});
|
||||
|
||||
fixture.detectChanges();
|
||||
@@ -136,7 +122,7 @@ describe('ModalHostComponent', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
data: { title: 'Persistente' },
|
||||
closeOnBackdrop: false
|
||||
closeOnBackdrop: false,
|
||||
});
|
||||
|
||||
fixture.detectChanges();
|
||||
@@ -152,7 +138,7 @@ describe('ModalHostComponent', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
data: { title: 'Escape' },
|
||||
closeOnEscape: true
|
||||
closeOnEscape: true,
|
||||
});
|
||||
|
||||
fixture.detectChanges();
|
||||
@@ -167,7 +153,7 @@ describe('ModalHostComponent', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
data: { title: 'No Escape' },
|
||||
closeOnEscape: false
|
||||
closeOnEscape: false,
|
||||
});
|
||||
|
||||
fixture.detectChanges();
|
||||
@@ -181,12 +167,13 @@ describe('ModalHostComponent', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
title: 'Con cierre',
|
||||
data: { title: 'Boton' }
|
||||
data: { title: 'Boton' },
|
||||
});
|
||||
|
||||
fixture.detectChanges();
|
||||
|
||||
const closeButton = fixture.debugElement.query(By.css('.btn-close')).nativeElement as HTMLButtonElement;
|
||||
const closeButton = fixture.debugElement.query(By.css('.btn-close'))
|
||||
.nativeElement as HTMLButtonElement;
|
||||
closeButton.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
|
||||
@@ -7,21 +7,17 @@ import {
|
||||
computed,
|
||||
effect,
|
||||
inject,
|
||||
viewChild
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
|
||||
import {
|
||||
MODAL_DATA,
|
||||
ModalRef,
|
||||
ModalService
|
||||
} from '../../../core/services/modal.service';
|
||||
import { MODAL_DATA, ModalRef, ModalService } from '../../../core/services/modal.service';
|
||||
import { ModalShellComponent } from '../modal-shell/modal-shell.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-modal-host',
|
||||
imports: [NgComponentOutlet, ModalShellComponent],
|
||||
templateUrl: './modal-host.component.html',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class ModalHostComponent {
|
||||
private readonly modalService = inject(ModalService);
|
||||
@@ -42,9 +38,9 @@ export class ModalHostComponent {
|
||||
return Injector.create({
|
||||
providers: [
|
||||
{ provide: ModalRef, useValue: modal.ref },
|
||||
{ provide: MODAL_DATA, useValue: modal.config.data ?? null }
|
||||
{ provide: MODAL_DATA, useValue: modal.config.data ?? null },
|
||||
],
|
||||
parent: this.injector
|
||||
parent: this.injector,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -58,6 +54,18 @@ export class ModalHostComponent {
|
||||
|
||||
const body = this.document.body;
|
||||
const previousOverflow = body.style.overflow;
|
||||
const previousPaddingRight = body.style.paddingRight;
|
||||
const view = this.document.defaultView;
|
||||
const scrollbarWidth = view
|
||||
? Math.max(0, view.innerWidth - this.document.documentElement.clientWidth)
|
||||
: 0;
|
||||
|
||||
if (scrollbarWidth > 0 && view) {
|
||||
const currentPaddingRight =
|
||||
Number.parseFloat(view.getComputedStyle(body).paddingRight) || 0;
|
||||
body.style.paddingRight = `${currentPaddingRight + scrollbarWidth}px`;
|
||||
}
|
||||
|
||||
body.style.overflow = 'hidden';
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
@@ -75,6 +83,7 @@ export class ModalHostComponent {
|
||||
onCleanup(() => {
|
||||
this.document.removeEventListener('keydown', onKeyDown);
|
||||
body.style.overflow = previousOverflow;
|
||||
body.style.paddingRight = previousPaddingRight;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,8 +10,7 @@
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1rem;
|
||||
background: rgba(16, 18, 22, 0.48);
|
||||
backdrop-filter: blur(2px);
|
||||
background: rgba(16, 18, 22, 0.56);
|
||||
}
|
||||
|
||||
.modal-shell__dialog {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
[title]="item.nombre"
|
||||
[description]="item.descripcion ?? ''"
|
||||
[price]="price(item)"
|
||||
[variants]="variantsFor(item)"
|
||||
[variants]="item.variants ?? []"
|
||||
(buy)="emitRowBuy(item, $event)"
|
||||
(addToCart)="emitRowCart(item, $event)"
|
||||
/>
|
||||
@@ -27,6 +27,18 @@
|
||||
(addToCart)="emitColumnCart(item, $event)"
|
||||
/>
|
||||
}
|
||||
@case ('ticket_selector') {
|
||||
<app-product-ticket-selector
|
||||
[title]="item.nombre"
|
||||
[description]="item.descripcion ?? ''"
|
||||
[price]="price(item)"
|
||||
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
||||
[variants]="item.variants ?? []"
|
||||
[unavailableVariantIds]="unavailableVariantIds()"
|
||||
[disabled]="loading()"
|
||||
(buy)="emitTicketBuy(item, $event)"
|
||||
/>
|
||||
}
|
||||
@default {
|
||||
<app-product-column-with-image
|
||||
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
||||
@@ -54,8 +66,11 @@
|
||||
class="product-list"
|
||||
[class.product-list--row]="effectiveLayout() === 'row'"
|
||||
[class.product-list--column]="effectiveLayout() !== 'row'"
|
||||
[class.product-list--adaptive]="groupLayout() !== 'simple_vertical'"
|
||||
[class.product-list--adaptive]="
|
||||
groupLayout() !== 'simple_vertical' && groupLayout() !== 'single'
|
||||
"
|
||||
[class.product-list--simple-vertical]="groupLayout() === 'simple_vertical'"
|
||||
[class.product-list--single]="groupLayout() === 'single'"
|
||||
>
|
||||
@for (item of itemData(); track item.id; let index = $index) {
|
||||
<ng-container
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
|
||||
&--row {
|
||||
--product-list-item-min-width: 32rem;
|
||||
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
&--adaptive {
|
||||
@@ -25,6 +27,10 @@
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
&--single {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
&__item {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
|
||||
@@ -8,11 +8,14 @@ import {
|
||||
CatalogGroupLayout,
|
||||
} from '../../../core/services/catalog/catalog.interface';
|
||||
import { ProductListComponent, ProductListItem, ProductListLayout } from './product-list.component';
|
||||
import { ProductTicketSelectorComponent } from '../product-ticket-selector/product-ticket-selector.component';
|
||||
import { By } from '@angular/platform-browser';
|
||||
|
||||
describe('ProductListComponent', () => {
|
||||
const items: ProductListItem[] = [
|
||||
{
|
||||
id: 1,
|
||||
type: 'product',
|
||||
nombre: 'Producto uno',
|
||||
descripcion: 'Primera descripcion',
|
||||
precio: '100.00',
|
||||
@@ -21,6 +24,7 @@ describe('ProductListComponent', () => {
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
type: 'product',
|
||||
nombre: 'Producto dos',
|
||||
descripcion: 'Segunda descripcion',
|
||||
precio: 200,
|
||||
@@ -216,6 +220,93 @@ describe('ProductListComponent', () => {
|
||||
expect(element.querySelectorAll('app-product-column-with-image')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('renders a single ticket selector and emits its selected variant', async () => {
|
||||
const ticket: ProductListItem = {
|
||||
...items[0],
|
||||
variants: [
|
||||
{
|
||||
id: 401,
|
||||
precio: '10000.00',
|
||||
stock_tecnico: 1,
|
||||
values: {
|
||||
tipo: { value: 'vip', label: 'VIP' },
|
||||
sector: { value: 'a', label: 'Sector A' },
|
||||
fila: { value: '3', label: 'Fila 3' },
|
||||
asiento: { value: '12', label: 'Asiento 12' },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 402,
|
||||
precio: '12000.00',
|
||||
stock_tecnico: 1,
|
||||
values: {
|
||||
tipo: { value: 'vip', label: 'VIP' },
|
||||
sector: { value: 'a', label: 'Sector A' },
|
||||
fila: { value: '3', label: 'Fila 3' },
|
||||
asiento: { value: '13', label: 'Asiento 13' },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const fixture = await render('ticket_selector', [ticket], 'single');
|
||||
const buySpy = vi.fn();
|
||||
fixture.componentInstance.buy.subscribe(buySpy);
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
|
||||
expect(element.querySelector('.product-list--single')).not.toBeNull();
|
||||
expect(element.querySelectorAll('app-product-ticket-selector')).toHaveLength(1);
|
||||
expect(element.querySelectorAll('.variant-selector__select')).toHaveLength(4);
|
||||
expect(
|
||||
(element.querySelector('.ticket-selector__actions .btn-primary') as HTMLButtonElement)
|
||||
.disabled,
|
||||
).toBe(true);
|
||||
|
||||
const ticketSelector = fixture.debugElement.query(By.directive(ProductTicketSelectorComponent))
|
||||
.componentInstance as ProductTicketSelectorComponent;
|
||||
ticketSelector['updateRow'](1, 401);
|
||||
fixture.detectChanges();
|
||||
|
||||
(element.querySelector('.ticket-selector__add-row-button') as HTMLButtonElement).click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(element.querySelectorAll('.ticket-selector__row')).toHaveLength(2);
|
||||
expect(element.querySelectorAll('.variant-selector__select')).toHaveLength(8);
|
||||
|
||||
ticketSelector['updateRow'](2, 402);
|
||||
fixture.detectChanges();
|
||||
|
||||
(element.querySelector('.ticket-selector__actions .btn-primary') as HTMLButtonElement).click();
|
||||
|
||||
expect(buySpy).toHaveBeenCalledWith({
|
||||
product: ticket,
|
||||
quantity: 2,
|
||||
variant: 401,
|
||||
variantIds: [401, 402],
|
||||
directPurchase: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('removes unavailable variants from the ticket selector', async () => {
|
||||
const ticket: ProductListItem = {
|
||||
...items[0],
|
||||
variants: [
|
||||
{ id: 401, stock_tecnico: 1, values: { asiento: { value: '1', label: '1' } } },
|
||||
{ id: 402, stock_tecnico: 1, values: { asiento: { value: '2', label: '2' } } },
|
||||
],
|
||||
};
|
||||
const fixture = await render('ticket_selector', [ticket], 'single');
|
||||
fixture.componentRef.setInput('unavailableVariantIds', new Set([401]));
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
|
||||
const selector = fixture.debugElement.query(By.directive(ProductTicketSelectorComponent))
|
||||
.componentInstance as ProductTicketSelectorComponent;
|
||||
|
||||
expect(selector['selectableVariants']().map((variant) => variant.id)).toEqual([402]);
|
||||
});
|
||||
|
||||
it('renders carousel groups with the reusable carousel', async () => {
|
||||
const fixture = await render('column_with_image', items, 'carousel');
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
|
||||
@@ -21,11 +21,9 @@ import {
|
||||
import { CarouselComponent } from '../carousel/carousel.component';
|
||||
import { PaginatorComponent } from '../paginator/paginator.component';
|
||||
import { ProductColumnWithImageComponent } from '../product-column-with-image/product-column-with-image.component';
|
||||
import {
|
||||
ProductRowCardComponent,
|
||||
Variant as RowVariant,
|
||||
} from '../product-row-card/product-row-card.component';
|
||||
import { ProductRowCardComponent } from '../product-row-card/product-row-card.component';
|
||||
import { ProductVerticalWithCartCardComponent } from '../product-vertical-with-cart-card/product-vertical-with-cart-card.component';
|
||||
import { ProductTicketSelectorComponent } from '../product-ticket-selector/product-ticket-selector.component';
|
||||
|
||||
export type ProductListLayout = CatalogProductLayout;
|
||||
export type ProductListVariant = CatalogFeaturedItemVariant;
|
||||
@@ -41,6 +39,7 @@ export interface ProductListBuyEvent {
|
||||
product: ProductListItem;
|
||||
quantity: number;
|
||||
variant?: number | null;
|
||||
variantIds?: number[];
|
||||
directPurchase: boolean;
|
||||
}
|
||||
|
||||
@@ -53,6 +52,7 @@ export interface ProductListBuyEvent {
|
||||
PaginatorComponent,
|
||||
ProductRowCardComponent,
|
||||
ProductVerticalWithCartCardComponent,
|
||||
ProductTicketSelectorComponent,
|
||||
],
|
||||
templateUrl: './product-list.component.html',
|
||||
styleUrl: './product-list.component.scss',
|
||||
@@ -67,6 +67,7 @@ export class ProductListComponent {
|
||||
readonly items = input.required<CatalogFeaturedItems>();
|
||||
readonly loading = input(false);
|
||||
readonly loadImages = input(true);
|
||||
readonly unavailableVariantIds = input<ReadonlySet<number>>(new Set<number>());
|
||||
|
||||
readonly buy = output<ProductListBuyEvent>();
|
||||
readonly addToCart = output<ProductListCartEvent>();
|
||||
@@ -105,13 +106,6 @@ export class ProductListComponent {
|
||||
return Number.isFinite(price) ? price : 0;
|
||||
}
|
||||
|
||||
protected variantsFor(item: ProductListItem): RowVariant[] {
|
||||
return (item.variants ?? []).map((variant) => ({
|
||||
value: variant.id,
|
||||
label: Object.values(variant.values).join(' / ') || `Variante ${variant.id}`,
|
||||
}));
|
||||
}
|
||||
|
||||
protected emitRowCart(
|
||||
product: ProductListItem,
|
||||
event: { quantity: number; variant: unknown },
|
||||
@@ -157,4 +151,14 @@ export class ProductListComponent {
|
||||
protected emitProductDetailBuy(product: ProductListItem): void {
|
||||
this.buy.emit({ product, quantity: 1, variant: null, directPurchase: false });
|
||||
}
|
||||
|
||||
protected emitTicketBuy(product: ProductListItem, variantIds: number[]): void {
|
||||
this.buy.emit({
|
||||
product,
|
||||
quantity: variantIds.length,
|
||||
variant: variantIds[0] ?? null,
|
||||
variantIds,
|
||||
directPurchase: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,42 +1,38 @@
|
||||
<div
|
||||
class="product-row-card border rounded bg-white shadow-sm d-flex justify-content-between p-3 gap-3"
|
||||
>
|
||||
<div class="product-row-card">
|
||||
<!-- Left Side: Title and Description -->
|
||||
<div class="product-row-card__info d-flex flex-column justify-content-center flex-grow-1">
|
||||
<h3 class="product-row-card__title text-uppercase mb-1 m-0">
|
||||
{{ title() }}
|
||||
</h3>
|
||||
@if (description()) {
|
||||
@if (effectiveDescription()) {
|
||||
<p class="product-row-card__description m-0 mt-1">
|
||||
{{ description() }}
|
||||
{{ effectiveDescription() }}
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Right Side: Actions and Pricing -->
|
||||
<div class="product-row-card__actions d-flex flex-column gap-2 justify-content-center">
|
||||
<!-- Top Row: Price and Comprar button -->
|
||||
<div class="d-flex align-items-center justify-content-end gap-3">
|
||||
<!-- Right Side: Selectors and quantity first, then price -->
|
||||
<div class="product-row-card__actions">
|
||||
<div class="product-row-card__summary">
|
||||
<div class="product-row-card__controls">
|
||||
<app-variant-selector
|
||||
class="product-row-card__selectors"
|
||||
[variants]="variants()"
|
||||
[(selectedVariant)]="selectedVariant"
|
||||
/>
|
||||
|
||||
<app-quantity-selector [(quantity)]="quantity"></app-quantity-selector>
|
||||
</div>
|
||||
|
||||
<span class="product-row-card__price text-primary">
|
||||
{{ formattedPrice() }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="product-row-card__buttons">
|
||||
<div class="product-row-card__btn-wrapper">
|
||||
<app-button variant="primary" (click)="onBuy()"> Comprar </app-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bottom Row: Select, Quantity, and Agregar al carrito button -->
|
||||
<div class="d-flex align-items-center justify-content-end gap-2">
|
||||
@if (variants().length > 0) {
|
||||
<select class="form-select product-row-card__select" [(ngModel)]="selectedVariant">
|
||||
@for (variant of variants(); track variant.value) {
|
||||
<option [ngValue]="variant.value">{{ variant.label }}</option>
|
||||
}
|
||||
</select>
|
||||
}
|
||||
|
||||
<app-quantity-selector [(quantity)]="quantity"></app-quantity-selector>
|
||||
|
||||
<div class="product-row-card__btn-wrapper">
|
||||
<app-button variant="secondary" (click)="onAddToCart()"> Agregar al carrito </app-button>
|
||||
</div>
|
||||
|
||||
@@ -4,9 +4,14 @@
|
||||
}
|
||||
|
||||
.product-row-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 2rem;
|
||||
width: 100%;
|
||||
background-color: #f8f9fa; /* slightly light bg matching the screenshot if needed, but let's use white or #f8f9fa based on the border */
|
||||
border-color: #e9ecef !important;
|
||||
padding: 2rem 0;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
background: transparent;
|
||||
|
||||
&__title {
|
||||
font-size: 16px;
|
||||
@@ -20,35 +25,48 @@
|
||||
color: #777; /* lighter grey for text */
|
||||
line-height: 1.4;
|
||||
max-width: 600px;
|
||||
|
||||
|
||||
/* Simulate the bold text for 'Niños menores...' if it was HTML.
|
||||
Since it's passed as string we just let it be, unless we parse it. */
|
||||
}
|
||||
|
||||
&__price {
|
||||
display: block;
|
||||
align-self: flex-end;
|
||||
font-size: 20px;
|
||||
font-weight: 800;
|
||||
color: var(--tenant-primary, #009933) !important; /* Green matching screenshot */
|
||||
color: var(--tenant-primary, #009933) !important;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&__select {
|
||||
width: auto;
|
||||
min-width: 150px;
|
||||
font-size: 14px;
|
||||
height: 38px;
|
||||
color: #666;
|
||||
border-color: #ccc;
|
||||
cursor: pointer;
|
||||
&__actions {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, auto) minmax(0, 230px);
|
||||
align-items: stretch;
|
||||
gap: 0.75rem 2.5rem;
|
||||
}
|
||||
|
||||
&:focus {
|
||||
border-color: var(--tenant-primary);
|
||||
box-shadow: 0 0 0 0.25rem rgba(0, 153, 51, 0.25);
|
||||
}
|
||||
&__summary,
|
||||
&__buttons {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
&__buttons {
|
||||
width: 100%;
|
||||
max-width: 230px;
|
||||
}
|
||||
|
||||
&__controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
&__btn-wrapper {
|
||||
min-width: 160px; /* To make both buttons equal width as in screenshot */
|
||||
|
||||
app-button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
@@ -61,3 +79,41 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 992px) {
|
||||
.product-row-card {
|
||||
&__info {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
&__actions {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
&__selectors {
|
||||
width: auto;
|
||||
|
||||
::ng-deep .variant-selector {
|
||||
display: flex;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
::ng-deep .variant-selector__select {
|
||||
width: auto;
|
||||
min-width: 108px;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 991.98px) {
|
||||
.product-row-card {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
|
||||
&__actions {
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 230px);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,22 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
effect,
|
||||
input,
|
||||
output,
|
||||
model,
|
||||
} from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ChangeDetectionStrategy, Component, computed, input, model, output } from '@angular/core';
|
||||
import { ButtonComponent } from '../button/button.component';
|
||||
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
||||
import {
|
||||
VariantSelectorComponent,
|
||||
VariantSelectorVariant,
|
||||
} from '../variant-selector/variant-selector.component';
|
||||
|
||||
export interface Variant {
|
||||
label: string;
|
||||
value: any;
|
||||
export interface Variant extends VariantSelectorVariant {
|
||||
label?: string;
|
||||
descripcion?: string | null;
|
||||
precio?: string | number;
|
||||
stock_tecnico?: number | null;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-product-row-card',
|
||||
standalone: true,
|
||||
imports: [ButtonComponent, QuantitySelectorComponent, FormsModule],
|
||||
imports: [ButtonComponent, QuantitySelectorComponent, VariantSelectorComponent],
|
||||
templateUrl: './product-row-card.component.html',
|
||||
styleUrl: './product-row-card.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
@@ -33,31 +30,26 @@ export class ProductRowCardComponent {
|
||||
|
||||
// Internal state models
|
||||
readonly quantity = model<number>(1);
|
||||
readonly selectedVariant = model<any>(null);
|
||||
readonly selectedVariant = model<unknown>(null);
|
||||
|
||||
// Interactive events
|
||||
readonly buy = output<{ quantity: number; variant: any }>();
|
||||
readonly addToCart = output<{ quantity: number; variant: any }>();
|
||||
readonly buy = output<{ quantity: number; variant: unknown }>();
|
||||
readonly addToCart = output<{ quantity: number; variant: unknown }>();
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const variants = this.variants();
|
||||
const selectedVariant = this.selectedVariant();
|
||||
protected readonly selectedVariantData = computed(() =>
|
||||
this.variants().find((variant) => Object.is(variant.id, this.selectedVariant())),
|
||||
);
|
||||
protected readonly effectiveDescription = computed(
|
||||
() => this.selectedVariantData()?.descripcion ?? this.description(),
|
||||
);
|
||||
protected readonly effectivePrice = computed(() => {
|
||||
const variantPrice = Number(this.selectedVariantData()?.precio);
|
||||
|
||||
if (
|
||||
variants.length > 0 &&
|
||||
!variants.some((variant) => Object.is(variant.value, selectedVariant))
|
||||
) {
|
||||
this.selectedVariant.set(variants[0].value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Formatted string for price: "$ 10.000"
|
||||
readonly formattedPrice = computed(() => {
|
||||
return this.formatCurrency(this.price());
|
||||
return Number.isFinite(variantPrice) ? variantPrice : this.price();
|
||||
});
|
||||
|
||||
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||
|
||||
protected onAddToCart(): void {
|
||||
this.addToCart.emit({
|
||||
quantity: this.quantity(),
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
<article class="ticket-selector">
|
||||
<header class="ticket-selector__header">
|
||||
<div>
|
||||
<h3 class="ticket-selector__title">{{ title() }}</h3>
|
||||
@if (description()) {
|
||||
<p class="ticket-selector__description">{{ description() }}</p>
|
||||
}
|
||||
</div>
|
||||
<span class="ticket-selector__price text-primary">
|
||||
@if (priceRange().hasRange) {
|
||||
de <strong>{{ priceRange().minimum }}</strong> a
|
||||
<strong>{{ priceRange().maximum }}</strong>
|
||||
} @else {
|
||||
<strong>{{ priceRange().minimum }}</strong>
|
||||
}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div class="ticket-selector__selection">
|
||||
<span class="ticket-selector__label">Seleccioná Entrada/s:</span>
|
||||
|
||||
<div class="ticket-selector__rows">
|
||||
@for (row of rows(); track row.id) {
|
||||
<div class="ticket-selector__row">
|
||||
<app-variant-selector
|
||||
class="ticket-selector__fields"
|
||||
[variants]="variantsForRow(row.id)"
|
||||
[disabled]="disabled()"
|
||||
[autoSelectFirst]="false"
|
||||
[selectedVariant]="row.variantId"
|
||||
(selectedVariantChange)="updateRow(row.id, $event)"
|
||||
/>
|
||||
<app-icon-button
|
||||
variant="trash"
|
||||
ariaLabel="Eliminar entrada"
|
||||
[disabled]="disabled()"
|
||||
(clicked)="removeRow(row.id)"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<app-button
|
||||
hostClass="ticket-selector__add-row"
|
||||
buttonClass="ticket-selector__add-row-button"
|
||||
variant="secondary"
|
||||
[disabled]="disabled() || !canAddRow()"
|
||||
(click)="addRow()"
|
||||
>
|
||||
+ Agregar entrada
|
||||
</app-button>
|
||||
|
||||
@if (selectableVariants().length === 0) {
|
||||
<p class="ticket-selector__empty">No hay entradas disponibles.</p>
|
||||
}
|
||||
|
||||
<div class="ticket-selector__actions row g-0 justify-content-end">
|
||||
<div class="col-12 col-md-3">
|
||||
<app-button variant="primary" [disabled]="disabled() || !hasSelection()" (click)="onBuy()">
|
||||
Comprar
|
||||
</app-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (imageUrl(); as image) {
|
||||
<img class="ticket-selector__map" [src]="image" [alt]="'Plano de ubicaciones de ' + title()" />
|
||||
}
|
||||
</article>
|
||||
@@ -0,0 +1,122 @@
|
||||
:host {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.ticket-selector {
|
||||
width: 100%;
|
||||
|
||||
&__header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding-bottom: 1.25rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
&__title {
|
||||
margin: 0;
|
||||
color: #666;
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.4px;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
&__description {
|
||||
margin: 0.35rem 0 0;
|
||||
color: #777;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
&__price {
|
||||
flex: 0 0 auto;
|
||||
font-size: 25px;
|
||||
font-weight: 400;
|
||||
|
||||
strong {
|
||||
font-weight: 700;
|
||||
}
|
||||
}
|
||||
|
||||
&__selection {
|
||||
padding-top: 1rem;
|
||||
}
|
||||
|
||||
&__label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
color: #555;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
&__rows {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
&__row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: end;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
&__fields {
|
||||
min-width: 0;
|
||||
|
||||
::ng-deep .variant-selector {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(120px, 1fr));
|
||||
gap: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
&__add-row {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin-top: 0.5rem;
|
||||
|
||||
::ng-deep .ticket-selector__add-row-button {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
&__empty {
|
||||
margin: 0;
|
||||
color: #777;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
&__actions {
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
&__map {
|
||||
display: block;
|
||||
width: min(100%, 720px);
|
||||
max-height: 680px;
|
||||
margin: 3rem auto 0;
|
||||
object-fit: contain;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767.98px) {
|
||||
.ticket-selector {
|
||||
&__header {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
&__fields {
|
||||
::ng-deep .variant-selector {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
&__map {
|
||||
margin-top: 2rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
effect,
|
||||
input,
|
||||
output,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
|
||||
import { ButtonComponent } from '../button/button.component';
|
||||
import { IconButtonComponent } from '../icon-button/icon-button.component';
|
||||
import {
|
||||
VariantSelectorComponent,
|
||||
VariantSelectorVariant,
|
||||
} from '../variant-selector/variant-selector.component';
|
||||
|
||||
export interface TicketSelectorVariant extends VariantSelectorVariant {
|
||||
precio?: string | number;
|
||||
stock_tecnico?: number | null;
|
||||
}
|
||||
|
||||
interface TicketSelectionRow {
|
||||
id: number;
|
||||
variantId: number | null;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-product-ticket-selector',
|
||||
imports: [ButtonComponent, IconButtonComponent, VariantSelectorComponent],
|
||||
templateUrl: './product-ticket-selector.component.html',
|
||||
styleUrl: './product-ticket-selector.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class ProductTicketSelectorComponent {
|
||||
readonly title = input.required<string>();
|
||||
readonly description = input<string>('');
|
||||
readonly price = input<number>(0);
|
||||
readonly imageUrl = input<string | null>(null);
|
||||
readonly variants = input<TicketSelectorVariant[]>([]);
|
||||
readonly unavailableVariantIds = input<ReadonlySet<number>>(new Set<number>());
|
||||
readonly disabled = input(false);
|
||||
|
||||
readonly buy = output<number[]>();
|
||||
|
||||
protected readonly rows = signal<TicketSelectionRow[]>([{ id: 1, variantId: null }]);
|
||||
private nextRowId = 2;
|
||||
|
||||
protected readonly selectableVariants = computed<TicketSelectorVariant[]>(() =>
|
||||
this.variants().filter(
|
||||
(variant) =>
|
||||
!this.unavailableVariantIds().has(variant.id as number) &&
|
||||
(variant.stock_tecnico == null || variant.stock_tecnico > 0),
|
||||
),
|
||||
);
|
||||
protected readonly hasSelection = computed(
|
||||
() => this.rows().length > 0 && this.rows().every((row) => row.variantId !== null),
|
||||
);
|
||||
protected readonly canAddRow = computed(
|
||||
() => this.rows().length < this.selectableVariants().length,
|
||||
);
|
||||
protected readonly priceRange = computed(() => {
|
||||
const prices = this.selectableVariants()
|
||||
.map((variant) => Number(variant.precio ?? this.price()))
|
||||
.filter(Number.isFinite);
|
||||
|
||||
if (prices.length === 0) {
|
||||
const price = this.formatCurrency(this.price());
|
||||
return { minimum: price, maximum: price, hasRange: false };
|
||||
}
|
||||
|
||||
const minimum = Math.min(...prices);
|
||||
const maximum = Math.max(...prices);
|
||||
return {
|
||||
minimum: this.formatCurrency(minimum),
|
||||
maximum: this.formatCurrency(maximum),
|
||||
hasRange: minimum !== maximum,
|
||||
};
|
||||
});
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const unavailable = this.unavailableVariantIds();
|
||||
|
||||
if (!this.rows().some((row) => row.variantId !== null && unavailable.has(row.variantId))) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.rows.update((rows) =>
|
||||
rows.map((row) =>
|
||||
row.variantId !== null && unavailable.has(row.variantId)
|
||||
? { ...row, variantId: null }
|
||||
: row,
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
protected onBuy(): void {
|
||||
const variantIds = this.rows().flatMap((row) =>
|
||||
row.variantId === null ? [] : [row.variantId],
|
||||
);
|
||||
|
||||
if (variantIds.length === this.rows().length && variantIds.length > 0) {
|
||||
this.buy.emit(variantIds);
|
||||
}
|
||||
}
|
||||
|
||||
protected addRow(): void {
|
||||
if (!this.canAddRow()) return;
|
||||
this.rows.update((rows) => [...rows, { id: this.nextRowId++, variantId: null }]);
|
||||
}
|
||||
|
||||
protected removeRow(rowId: number): void {
|
||||
this.rows.update((rows) => rows.filter((row) => row.id !== rowId));
|
||||
}
|
||||
|
||||
protected updateRow(rowId: number, selectedVariant: unknown): void {
|
||||
const variantId = typeof selectedVariant === 'number' ? selectedVariant : null;
|
||||
this.rows.update((rows) => rows.map((row) => (row.id === rowId ? { ...row, variantId } : row)));
|
||||
}
|
||||
|
||||
protected variantsForRow(rowId: number): VariantSelectorVariant[] {
|
||||
const selectedByOtherRows = new Set(
|
||||
this.rows()
|
||||
.filter((row) => row.id !== rowId && row.variantId !== null)
|
||||
.map((row) => row.variantId),
|
||||
);
|
||||
|
||||
return this.selectableVariants().filter(
|
||||
(variant) => !selectedByOtherRows.has(variant.id as number),
|
||||
);
|
||||
}
|
||||
|
||||
private formatCurrency(value: number): string {
|
||||
return new Intl.NumberFormat('es-AR', {
|
||||
style: 'currency',
|
||||
currency: 'ARS',
|
||||
maximumFractionDigits: 0,
|
||||
}).format(value);
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
<div class="product-vertical-with-cart-card__content">
|
||||
<h3 class="product-vertical-with-cart-card__title">{{ title() }}</h3>
|
||||
|
||||
@if (description()) {
|
||||
<p class="product-vertical-with-cart-card__description">{{ description() }}</p>
|
||||
@if (effectiveDescription()) {
|
||||
<p class="product-vertical-with-cart-card__description">{{ effectiveDescription() }}</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -13,47 +13,15 @@
|
||||
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
||||
<app-quantity-selector [(quantity)]="quantity" />
|
||||
</div>
|
||||
} @else if (!hasMultipleVariantSelectors()) {
|
||||
<div class="product-vertical-with-cart-card__single-variant">
|
||||
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
||||
|
||||
<div class="product-vertical-with-cart-card__single-variant-row">
|
||||
@for (selector of variantSelectors(); track selector.key) {
|
||||
<select
|
||||
class="form-select product-vertical-with-cart-card__variant-select"
|
||||
[attr.aria-label]="selector.label"
|
||||
[ngModel]="selectedValues()[selector.key]"
|
||||
(ngModelChange)="onVariantValueChange(selector.key, $event)"
|
||||
>
|
||||
@for (option of selector.options; track option) {
|
||||
<option [ngValue]="option">{{ option }}</option>
|
||||
}
|
||||
</select>
|
||||
}
|
||||
|
||||
<app-quantity-selector [(quantity)]="quantity" />
|
||||
</div>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="product-vertical-with-cart-card__multiple-variants">
|
||||
<div class="product-vertical-with-cart-card__summary-column">
|
||||
<div class="product-vertical-with-cart-card__variants">
|
||||
<div class="product-vertical-with-cart-card__summary">
|
||||
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
||||
<app-quantity-selector [(quantity)]="quantity" />
|
||||
</div>
|
||||
|
||||
<div class="product-vertical-with-cart-card__variant-selectors">
|
||||
@for (selector of variantSelectors(); track selector.key) {
|
||||
<select
|
||||
class="form-select product-vertical-with-cart-card__variant-select"
|
||||
[attr.aria-label]="selector.label"
|
||||
[ngModel]="selectedValues()[selector.key]"
|
||||
(ngModelChange)="onVariantValueChange(selector.key, $event)"
|
||||
>
|
||||
@for (option of selector.options; track option) {
|
||||
<option [ngValue]="option">{{ option }}</option>
|
||||
}
|
||||
</select>
|
||||
}
|
||||
<app-variant-selector [variants]="variants()" [(selectedVariant)]="selectedVariant" />
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
padding: 30px 20px;
|
||||
overflow: hidden;
|
||||
background-color: #ffffff;
|
||||
border: 1px solid #dedede;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 7px;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
|
||||
|
||||
@@ -60,59 +60,17 @@
|
||||
padding-inline: 12px;
|
||||
}
|
||||
|
||||
&__single-variant {
|
||||
&__variants {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
&__single-variant-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
&__variant-selectors {
|
||||
width: 100%;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__multiple-variants {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
&__summary-column,
|
||||
&__variant-selectors {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
&__variant-selectors {
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
&__variant-select {
|
||||
min-width: 0;
|
||||
height: 40px;
|
||||
border-color: #d8d8d8;
|
||||
color: #6f6f6f;
|
||||
font-size: 12px;
|
||||
|
||||
&:focus {
|
||||
border-color: var(--tenant-primary, #009933);
|
||||
box-shadow: 0 0 0 0.2rem color-mix(in srgb, transparent 75%, var(--tenant-primary, #009933));
|
||||
}
|
||||
}
|
||||
|
||||
&__single-variant-row &__variant-select {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
&__single-variant-row app-quantity-selector {
|
||||
flex: 0 0 auto;
|
||||
&__variant-selectors app-variant-selector {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
&__price {
|
||||
@@ -145,6 +103,16 @@
|
||||
@media (max-width: 767.98px) {
|
||||
.product-vertical-with-cart-card {
|
||||
border-color: var(--color-primary, var(--tenant-primary, #009933));
|
||||
|
||||
&__title {
|
||||
color: var(--color-primary, var(--tenant-primary, #009933));
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
&__description {
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
@@ -17,7 +17,7 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
async function createComponent(description = 'Pancho con aderezo a elección.') {
|
||||
async function createComponent(description = 'Pancho con aderezo a elección.') {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [ProductVerticalWithCartCardComponent],
|
||||
}).compileComponents();
|
||||
@@ -40,7 +40,7 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
||||
);
|
||||
expect(
|
||||
element.querySelector('.product-vertical-with-cart-card__description')?.textContent,
|
||||
).toContain('Pancho con aderezo a elección.');
|
||||
).toContain('Pancho con aderezo a elección.');
|
||||
expect(
|
||||
element.querySelector('.product-vertical-with-cart-card__price')?.textContent?.trim(),
|
||||
).toBe('$ 11.500');
|
||||
@@ -116,7 +116,7 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
||||
).not.toBeNull();
|
||||
});
|
||||
|
||||
it('places a single variant selector in the same row as the quantity', async () => {
|
||||
it('places price and quantity together above a single variant selector', async () => {
|
||||
const fixture = await createComponent();
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{ id: 10, values: { fecha: '10 de octubre' } },
|
||||
@@ -125,31 +125,31 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
const row = element.querySelector('.product-vertical-with-cart-card__single-variant-row');
|
||||
const summary = element.querySelector('.product-vertical-with-cart-card__summary');
|
||||
const selectors = element.querySelector('.product-vertical-with-cart-card__variant-selectors');
|
||||
|
||||
expect(row?.querySelectorAll('.product-vertical-with-cart-card__variant-select')).toHaveLength(
|
||||
1,
|
||||
);
|
||||
expect(row?.querySelector('app-quantity-selector')).not.toBeNull();
|
||||
expect(element.querySelector('.product-vertical-with-cart-card__multiple-variants')).toBeNull();
|
||||
expect(summary?.querySelector('.product-vertical-with-cart-card__price')).not.toBeNull();
|
||||
expect(summary?.querySelector('app-quantity-selector')).not.toBeNull();
|
||||
expect(selectors?.querySelectorAll('.variant-selector__select')).toHaveLength(1);
|
||||
expect(selectors?.querySelector('app-quantity-selector')).toBeNull();
|
||||
});
|
||||
|
||||
it('uses separate summary and selector columns for multiple variant attributes', async () => {
|
||||
it('places all variant selectors together below price and quantity', async () => {
|
||||
const fixture = await createComponent();
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{ id: 20, values: { fecha: '10 de octubre', turno: 'Mañana' } },
|
||||
{ id: 20, values: { fecha: '10 de octubre', turno: 'Mañana' } },
|
||||
{ id: 21, values: { fecha: '10 de octubre', turno: 'Tarde' } },
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
const layout = element.querySelector('.product-vertical-with-cart-card__multiple-variants');
|
||||
const layout = element.querySelector('.product-vertical-with-cart-card__variants');
|
||||
|
||||
expect(layout?.querySelector('.product-vertical-with-cart-card__summary')).not.toBeNull();
|
||||
expect(
|
||||
layout?.querySelector('.product-vertical-with-cart-card__summary-column'),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
layout?.querySelectorAll('.product-vertical-with-cart-card__variant-select'),
|
||||
layout?.querySelectorAll(
|
||||
'.product-vertical-with-cart-card__variant-selectors .variant-selector__select',
|
||||
),
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
@@ -164,7 +164,7 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
||||
fixture.componentInstance.buy.subscribe(buySpy);
|
||||
|
||||
const select = fixture.nativeElement.querySelector(
|
||||
'.product-vertical-with-cart-card__variant-select',
|
||||
'.variant-selector__select',
|
||||
) as HTMLSelectElement;
|
||||
select.value = select.options[1].value;
|
||||
select.dispatchEvent(new Event('change'));
|
||||
@@ -177,4 +177,43 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
||||
|
||||
expect(buySpy).toHaveBeenCalledWith({ quantity: 1, variant: 31 });
|
||||
});
|
||||
|
||||
it('prioritizes the selected variant description and price', async () => {
|
||||
const fixture = await createComponent('Descripción general');
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{
|
||||
id: 40,
|
||||
descripcion: 'Almuerzo en comedor',
|
||||
precio: '10000.00',
|
||||
values: { servicio: 'Comedor' },
|
||||
},
|
||||
{
|
||||
id: 41,
|
||||
descripcion: 'Almuerzo en vianda',
|
||||
precio: '8000.00',
|
||||
values: { servicio: 'Vianda' },
|
||||
},
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
expect(
|
||||
element.querySelector('.product-vertical-with-cart-card__description')?.textContent,
|
||||
).toContain('Almuerzo en comedor');
|
||||
expect(
|
||||
element.querySelector('.product-vertical-with-cart-card__price')?.textContent?.trim(),
|
||||
).toBe('$ 10.000');
|
||||
|
||||
const select = element.querySelector('.variant-selector__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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,33 +1,20 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
effect,
|
||||
input,
|
||||
model,
|
||||
output,
|
||||
signal,
|
||||
untracked,
|
||||
} from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ChangeDetectionStrategy, Component, computed, input, model, output } from '@angular/core';
|
||||
|
||||
import { ButtonComponent } from '../button/button.component';
|
||||
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
||||
import {
|
||||
VariantSelectorComponent,
|
||||
VariantSelectorVariant,
|
||||
} from '../variant-selector/variant-selector.component';
|
||||
|
||||
export interface VerticalCartVariant {
|
||||
id: number;
|
||||
values: Record<string, string>;
|
||||
}
|
||||
|
||||
interface VariantSelector {
|
||||
key: string;
|
||||
label: string;
|
||||
options: string[];
|
||||
export interface VerticalCartVariant extends VariantSelectorVariant {
|
||||
descripcion?: string | null;
|
||||
precio?: string | number;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-product-vertical-with-cart-card',
|
||||
imports: [ButtonComponent, FormsModule, QuantitySelectorComponent],
|
||||
imports: [ButtonComponent, QuantitySelectorComponent, VariantSelectorComponent],
|
||||
templateUrl: './product-vertical-with-cart-card.component.html',
|
||||
styleUrl: './product-vertical-with-cart-card.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
@@ -44,60 +31,19 @@ export class ProductVerticalWithCartCardComponent {
|
||||
readonly buy = output<{ quantity: number; variant: number | null }>();
|
||||
readonly addToCart = output<{ quantity: number; variant: number | null }>();
|
||||
|
||||
protected readonly selectedValues = signal<Record<string, string>>({});
|
||||
|
||||
protected readonly formattedPrice = computed(() => this.formatCurrency(this.price()));
|
||||
protected readonly variantSelectors = computed<VariantSelector[]>(() => {
|
||||
const variants = this.variants();
|
||||
const keys = Array.from(new Set(variants.flatMap((variant) => Object.keys(variant.values))));
|
||||
|
||||
return keys.map((key) => ({
|
||||
key,
|
||||
label: this.formatVariantLabel(key),
|
||||
options: Array.from(
|
||||
new Set(
|
||||
variants
|
||||
.map((variant) => variant.values[key])
|
||||
.filter((value): value is string => Boolean(value)),
|
||||
),
|
||||
),
|
||||
}));
|
||||
});
|
||||
|
||||
protected readonly hasVariants = computed(() => this.variantSelectors().length > 0);
|
||||
protected readonly hasMultipleVariantSelectors = computed(
|
||||
() => this.variantSelectors().length > 1,
|
||||
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);
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const variants = this.variants();
|
||||
|
||||
untracked(() => {
|
||||
if (variants.length === 0) {
|
||||
this.selectedValues.set({});
|
||||
this.selectedVariant.set(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const selected =
|
||||
variants.find((variant) => variant.id === this.selectedVariant()) ?? variants[0];
|
||||
this.selectedValues.set({ ...selected.values });
|
||||
this.selectedVariant.set(selected.id);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
protected onVariantValueChange(key: string, value: string): void {
|
||||
const values = { ...this.selectedValues(), [key]: value };
|
||||
const selectors = this.variantSelectors();
|
||||
const matchingVariant = this.variants().find((variant) =>
|
||||
selectors.every((selector) => variant.values[selector.key] === values[selector.key]),
|
||||
);
|
||||
|
||||
this.selectedValues.set(values);
|
||||
this.selectedVariant.set(matchingVariant?.id ?? null);
|
||||
}
|
||||
return Number.isFinite(variantPrice) ? variantPrice : this.price();
|
||||
});
|
||||
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||
protected readonly hasVariants = computed(() => this.variants().length > 0);
|
||||
|
||||
protected onAddToCart(): void {
|
||||
this.addToCart.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
|
||||
@@ -107,11 +53,6 @@ export class ProductVerticalWithCartCardComponent {
|
||||
this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
|
||||
}
|
||||
|
||||
private formatVariantLabel(key: string): string {
|
||||
const label = key.replace(/[_-]+/g, ' ');
|
||||
return label.charAt(0).toUpperCase() + label.slice(1);
|
||||
}
|
||||
|
||||
private formatCurrency(value: number): string {
|
||||
const rounded = Math.round(value);
|
||||
const parts = rounded.toString().split('.');
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
}
|
||||
|
||||
.quantity-selector {
|
||||
border: 1px solid #d8d8d8;
|
||||
border: 1px solid var(--border-color);
|
||||
width: 78px;
|
||||
height: 40px;
|
||||
min-height: 40px;
|
||||
background: inherit;
|
||||
background-color: #ffffff;
|
||||
box-sizing: border-box;
|
||||
|
||||
&__button {
|
||||
@@ -15,8 +15,10 @@
|
||||
height: 100%;
|
||||
font-size: 20px;
|
||||
color: #6f6f6f;
|
||||
background: inherit;
|
||||
transition: background-color 0.2s ease, color 0.2s ease;
|
||||
background-color: #ffffff;
|
||||
transition:
|
||||
background-color 0.2s ease,
|
||||
color 0.2s ease;
|
||||
cursor: pointer;
|
||||
|
||||
&:not(:disabled):hover {
|
||||
@@ -25,7 +27,7 @@
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
color: #A0A0A0;
|
||||
color: #a0a0a0;
|
||||
opacity: 1;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
@@ -37,16 +39,16 @@
|
||||
}
|
||||
|
||||
&--small {
|
||||
width: 46px;
|
||||
height: 21px;
|
||||
min-height: 21px;
|
||||
border: 1px solid #cfcfcf;
|
||||
background: inherit;
|
||||
width: 62px;
|
||||
height: 28px;
|
||||
min-height: 28px;
|
||||
border-color: var(--border-color);
|
||||
background-color: #ffffff;
|
||||
|
||||
.quantity-selector__button {
|
||||
width: 15px;
|
||||
font-size: 10px;
|
||||
background: inherit;
|
||||
width: 18px;
|
||||
font-size: 11px;
|
||||
background-color: #ffffff;
|
||||
color: #666666;
|
||||
|
||||
&:not(:disabled):hover {
|
||||
@@ -55,7 +57,7 @@
|
||||
}
|
||||
|
||||
.quantity-selector__value {
|
||||
font-size: 10px;
|
||||
font-size: 11px;
|
||||
color: #666666;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
@if (selectors().length > 0) {
|
||||
<div class="variant-selector" [class.variant-selector--compact]="compact()">
|
||||
@for (selector of selectors(); track selector.key) {
|
||||
<select
|
||||
class="form-select variant-selector__select"
|
||||
[attr.aria-label]="selector.label"
|
||||
[disabled]="disabled() || (!autoSelectFirst() && selector.options.length === 0)"
|
||||
[compareWith]="compareValues"
|
||||
[ngModel]="selectedValues()[selector.key] ?? null"
|
||||
(ngModelChange)="onValueChange(selector.key, $event)"
|
||||
>
|
||||
@if (!autoSelectFirst()) {
|
||||
<option [ngValue]="null" disabled>Seleccioná {{ selector.label }}</option>
|
||||
}
|
||||
@for (option of selector.options; track option.key) {
|
||||
<option [ngValue]="option.value">{{ option.label }}</option>
|
||||
}
|
||||
</select>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
:host {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.variant-selector {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.variant-selector__select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
height: 38px;
|
||||
color: #666666;
|
||||
border-color: var(--border-color);
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
|
||||
&:focus {
|
||||
border-color: var(--tenant-primary);
|
||||
box-shadow: 0 0 0 0.25rem rgba(0, 153, 51, 0.25);
|
||||
}
|
||||
|
||||
&:first-child:nth-last-child(odd) {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
|
||||
.variant-selector--compact {
|
||||
gap: 4px;
|
||||
|
||||
.variant-selector__select {
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
height: 28px;
|
||||
padding: 0.2rem 1.75rem 0.2rem 0.45rem;
|
||||
font-size: 11px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import '@angular/compiler';
|
||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
import { VariantSelectorComponent } from './variant-selector.component';
|
||||
|
||||
describe('VariantSelectorComponent', () => {
|
||||
beforeAll(() => {
|
||||
try {
|
||||
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
|
||||
} catch {
|
||||
// Test environment may already be initialized by another setup entrypoint.
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(() => TestBed.resetTestingModule());
|
||||
|
||||
it('updates following selections to the first compatible variant', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [VariantSelectorComponent],
|
||||
}).compileComponents();
|
||||
const fixture = TestBed.createComponent(VariantSelectorComponent);
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{ id: 1, values: { alojamiento: 'Carpa', servicio: 'Almuerzo' } },
|
||||
{ id: 2, values: { alojamiento: 'Carpa', servicio: 'Cena' } },
|
||||
{ id: 3, values: { alojamiento: 'Hotel', servicio: 'Cena' } },
|
||||
]);
|
||||
fixture.componentRef.setInput('selectedVariant', 1);
|
||||
fixture.detectChanges();
|
||||
|
||||
(fixture.componentInstance as any).onValueChange('alojamiento', 'Hotel');
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.componentInstance.selectedVariant()).toBe(3);
|
||||
expect((fixture.componentInstance as any).selectedValues()).toEqual({
|
||||
alojamiento: 'Hotel',
|
||||
servicio: 'Cena',
|
||||
});
|
||||
});
|
||||
|
||||
it('renders backend option labels and compares equivalent option objects by value', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [VariantSelectorComponent],
|
||||
}).compileComponents();
|
||||
const fixture = TestBed.createComponent(VariantSelectorComponent);
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{
|
||||
id: 1,
|
||||
values: {
|
||||
color: { value: 'red', label: 'Rojo' },
|
||||
talle: { value: 's', label: 'Small' },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
values: {
|
||||
color: { value: 'red', label: 'Rojo' },
|
||||
talle: { value: 'm', label: 'Medium' },
|
||||
},
|
||||
},
|
||||
]);
|
||||
fixture.componentRef.setInput('selectedVariant', 2);
|
||||
fixture.detectChanges();
|
||||
|
||||
const selects = Array.from(
|
||||
fixture.nativeElement.querySelectorAll('select'),
|
||||
) as HTMLSelectElement[];
|
||||
|
||||
expect(selects).toHaveLength(2);
|
||||
expect(selects[0].selectedOptions[0]?.textContent).toBe('Rojo');
|
||||
expect(selects[1].selectedOptions[0]?.textContent).toBe('Medium');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('[object Object]');
|
||||
|
||||
(fixture.componentInstance as any).onValueChange('talle', {
|
||||
value: 's',
|
||||
label: 'Small',
|
||||
});
|
||||
|
||||
expect(fixture.componentInstance.selectedVariant()).toBe(1);
|
||||
});
|
||||
|
||||
it('requires manual selections when autoSelectFirst is disabled', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [VariantSelectorComponent],
|
||||
}).compileComponents();
|
||||
const fixture = TestBed.createComponent(VariantSelectorComponent);
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{ id: 1, values: { sector: 'A', asiento: '1' } },
|
||||
{ id: 2, values: { sector: 'A', asiento: '2' } },
|
||||
]);
|
||||
fixture.componentRef.setInput('autoSelectFirst', false);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.componentInstance.selectedVariant()).toBeNull();
|
||||
expect((fixture.componentInstance as any).selectedValues()).toEqual({});
|
||||
|
||||
(fixture.componentInstance as any).onValueChange('sector', 'A');
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.componentInstance.selectedVariant()).toBeNull();
|
||||
expect((fixture.componentInstance as any).selectedValues()).toEqual({ sector: 'A' });
|
||||
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{ id: 1, values: { sector: 'A', asiento: '1' } },
|
||||
{ id: 2, values: { sector: 'A', asiento: '2' } },
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect((fixture.componentInstance as any).selectedValues()).toEqual({ sector: 'A' });
|
||||
expect((fixture.componentInstance as any).selectors()[1].options).toHaveLength(2);
|
||||
|
||||
(fixture.componentInstance as any).onValueChange('asiento', '2');
|
||||
|
||||
expect(fixture.componentInstance.selectedVariant()).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
effect,
|
||||
input,
|
||||
model,
|
||||
signal,
|
||||
untracked,
|
||||
} from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
|
||||
export interface VariantAttributeOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export type VariantAttributeScalar = string | VariantAttributeOption;
|
||||
export type VariantAttributeValue = VariantAttributeScalar | VariantAttributeScalar[];
|
||||
|
||||
export interface VariantSelectorVariant {
|
||||
id: unknown;
|
||||
values: Record<string, VariantAttributeValue>;
|
||||
}
|
||||
|
||||
interface VariantSelectorOption {
|
||||
key: string;
|
||||
label: string;
|
||||
value: VariantAttributeValue;
|
||||
}
|
||||
|
||||
interface VariantSelectorGroup {
|
||||
key: string;
|
||||
label: string;
|
||||
options: VariantSelectorOption[];
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-variant-selector',
|
||||
standalone: true,
|
||||
imports: [FormsModule],
|
||||
templateUrl: './variant-selector.component.html',
|
||||
styleUrl: './variant-selector.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class VariantSelectorComponent {
|
||||
readonly variants = input<VariantSelectorVariant[]>([]);
|
||||
readonly selectedVariant = model<unknown>(null);
|
||||
readonly disabled = input(false);
|
||||
readonly compact = input(false);
|
||||
readonly autoSelectFirst = input(true);
|
||||
|
||||
protected readonly selectedValues = signal<Record<string, VariantAttributeValue>>({});
|
||||
protected readonly compareValues = (
|
||||
left: VariantAttributeValue | null,
|
||||
right: VariantAttributeValue | null,
|
||||
): boolean => left !== null && right !== null && this.sameValue(left, right);
|
||||
protected readonly attributeKeys = computed(() =>
|
||||
Array.from(new Set(this.variants().flatMap((variant) => Object.keys(variant.values)))),
|
||||
);
|
||||
protected readonly selectors = computed<VariantSelectorGroup[]>(() => {
|
||||
const variants = this.variants();
|
||||
const keys = this.attributeKeys();
|
||||
const selectedValues = this.selectedValues();
|
||||
|
||||
return keys.map((key, index) => {
|
||||
const previousKeys = keys.slice(0, index);
|
||||
const compatibleVariants = variants.filter((variant) =>
|
||||
previousKeys.every((previousKey) =>
|
||||
this.sameValue(variant.values[previousKey], selectedValues[previousKey]),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
key,
|
||||
label: this.formatVariantLabel(key),
|
||||
options: this.optionsFor(compatibleVariants, key),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const variants = this.variants();
|
||||
const selectedVariant = this.selectedVariant();
|
||||
const autoSelectFirst = this.autoSelectFirst();
|
||||
|
||||
untracked(() => {
|
||||
if (variants.length === 0) {
|
||||
this.selectedValues.set({});
|
||||
if (selectedVariant !== null) this.selectedVariant.set(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const selected = variants.find((variant) => Object.is(variant.id, selectedVariant));
|
||||
|
||||
if (!selected && !autoSelectFirst) {
|
||||
this.selectedValues.set(this.reconcileManualSelection(this.selectedValues(), variants));
|
||||
if (selectedVariant !== null) this.selectedVariant.set(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const resolvedSelection = selected ?? variants[0];
|
||||
this.selectedValues.set({ ...resolvedSelection.values });
|
||||
if (!Object.is(resolvedSelection.id, selectedVariant)) {
|
||||
this.selectedVariant.set(resolvedSelection.id);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
protected onValueChange(key: string, value: VariantAttributeValue | null): void {
|
||||
const variants = this.variants();
|
||||
const keys = this.attributeKeys();
|
||||
const changedIndex = keys.indexOf(key);
|
||||
const values = { ...this.selectedValues() };
|
||||
|
||||
if (value === null) delete values[key];
|
||||
else values[key] = value;
|
||||
|
||||
for (let index = changedIndex + 1; index < keys.length; index++) {
|
||||
const currentKey = keys[index];
|
||||
const previousKeys = keys.slice(0, index);
|
||||
const compatibleVariants = variants.filter((variant) =>
|
||||
previousKeys.every((previousKey) =>
|
||||
this.sameValue(variant.values[previousKey], values[previousKey]),
|
||||
),
|
||||
);
|
||||
const options = this.optionsFor(compatibleVariants, currentKey);
|
||||
|
||||
if (!options.some((option) => this.sameValue(option.value, values[currentKey]))) {
|
||||
const firstOption = options[0];
|
||||
if (firstOption && this.autoSelectFirst()) values[currentKey] = firstOption.value;
|
||||
else delete values[currentKey];
|
||||
}
|
||||
}
|
||||
|
||||
const matchingVariant = variants.find((variant) =>
|
||||
keys.every((attributeKey) =>
|
||||
this.sameValue(variant.values[attributeKey], values[attributeKey]),
|
||||
),
|
||||
);
|
||||
|
||||
this.selectedValues.set(values);
|
||||
this.selectedVariant.set(matchingVariant?.id ?? null);
|
||||
}
|
||||
|
||||
private optionsFor(variants: VariantSelectorVariant[], key: string): VariantSelectorOption[] {
|
||||
const options = new Map<string, VariantSelectorOption>();
|
||||
|
||||
for (const variant of variants) {
|
||||
const value = variant.values[key];
|
||||
if (value === undefined || value === '') continue;
|
||||
|
||||
const optionKey = this.valueKey(value);
|
||||
if (!options.has(optionKey)) {
|
||||
options.set(optionKey, {
|
||||
key: optionKey,
|
||||
label: this.valueLabel(value),
|
||||
value,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(options.values());
|
||||
}
|
||||
|
||||
private reconcileManualSelection(
|
||||
selectedValues: Record<string, VariantAttributeValue>,
|
||||
variants: VariantSelectorVariant[],
|
||||
): Record<string, VariantAttributeValue> {
|
||||
const reconciled: Record<string, VariantAttributeValue> = {};
|
||||
|
||||
for (const key of this.attributeKeys()) {
|
||||
const selectedValue = selectedValues[key];
|
||||
if (selectedValue === undefined) break;
|
||||
|
||||
const compatibleVariants = variants.filter((variant) =>
|
||||
Object.entries(reconciled).every(([previousKey, previousValue]) =>
|
||||
this.sameValue(variant.values[previousKey], previousValue),
|
||||
),
|
||||
);
|
||||
const selectionIsAvailable = this.optionsFor(compatibleVariants, key).some((option) =>
|
||||
this.sameValue(option.value, selectedValue),
|
||||
);
|
||||
|
||||
if (!selectionIsAvailable) break;
|
||||
reconciled[key] = selectedValue;
|
||||
}
|
||||
|
||||
return reconciled;
|
||||
}
|
||||
|
||||
private sameValue(
|
||||
left: VariantAttributeValue | undefined,
|
||||
right: VariantAttributeValue | undefined,
|
||||
): boolean {
|
||||
return (
|
||||
left !== undefined && right !== undefined && this.valueKey(left) === this.valueKey(right)
|
||||
);
|
||||
}
|
||||
|
||||
private valueKey(value: VariantAttributeValue): string {
|
||||
const comparableValue = Array.isArray(value)
|
||||
? value.map((item) => this.scalarValue(item))
|
||||
: this.scalarValue(value);
|
||||
|
||||
return JSON.stringify(comparableValue);
|
||||
}
|
||||
|
||||
private valueLabel(value: VariantAttributeValue): string {
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
return values.map((item) => (typeof item === 'string' ? item : item.label)).join(', ');
|
||||
}
|
||||
|
||||
private scalarValue(value: VariantAttributeScalar): string {
|
||||
return typeof value === 'string' ? value : value.value;
|
||||
}
|
||||
|
||||
private formatVariantLabel(key: string): string {
|
||||
const label = key.replace(/[_-]+/g, ' ');
|
||||
return label.charAt(0).toUpperCase() + label.slice(1);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
export const environment = {
|
||||
production: false,
|
||||
nombre:"Homologación - activo",
|
||||
url:"https://backend.shopit.com.ar/api/",
|
||||
url:"https://backend.qa.shopit.com.ar/api/",
|
||||
urlDescarga:"url/"
|
||||
};
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
@use "./fonts";
|
||||
@use './fonts';
|
||||
|
||||
@import "@fortawesome/fontawesome-free/css/all.min.css";
|
||||
@import '@fortawesome/fontawesome-free/css/all.min.css';
|
||||
|
||||
@import "./theme";
|
||||
@import './theme';
|
||||
|
||||
@import "../node_modules/bootstrap/scss/bootstrap";
|
||||
@import '../node_modules/bootstrap/scss/bootstrap';
|
||||
|
||||
:root, app-root {
|
||||
--bs-body-font-family: "Gotham", sans-serif;
|
||||
:root,
|
||||
app-root {
|
||||
--border-color: #dddddd;
|
||||
--bs-border-color: var(--border-color);
|
||||
--bs-border-color-translucent: var(--border-color);
|
||||
--bs-body-font-family: 'Gotham', sans-serif;
|
||||
--color-primary: var(--tenant-primary);
|
||||
--color-primary-rgb: var(--tenant-primary-rgb);
|
||||
--color-secondary: var(--tenant-secondary);
|
||||
@@ -57,3 +61,23 @@ label {
|
||||
color: var(--color-danger, #dc3545);
|
||||
}
|
||||
}
|
||||
|
||||
.table-striped {
|
||||
--bs-table-bg: transparent;
|
||||
--bs-table-color: #8a8a8a;
|
||||
--bs-table-color-state: #8a8a8a;
|
||||
--bs-table-color-type: #8a8a8a;
|
||||
--bs-table-striped-bg: transparent;
|
||||
--bs-table-striped-color: #8a8a8a;
|
||||
|
||||
color: #8a8a8a;
|
||||
|
||||
> tbody > tr {
|
||||
border-radius: 0.5rem;
|
||||
clip-path: inset(0 round 0.5rem);
|
||||
}
|
||||
|
||||
> tbody > tr:nth-of-type(odd) {
|
||||
background-color: rgba(221, 221, 221, 0.25);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user