Compare commits
72 Commits
c645feba80
...
feature/ti
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ba2041f7b | |||
| 92ad7340fe | |||
| 6b2f8de210 | |||
| 69f3569ccf | |||
| 9937c1b484 | |||
| 43e497cf97 | |||
| 207c979f71 | |||
| 30bfd9eff8 | |||
| 3f8b5bf206 | |||
| d92b5a7623 | |||
| e4670491c7 | |||
| 1b94b2ca13 | |||
| 46dcb84985 | |||
| f7983b109f | |||
| 8ff9ed216c | |||
| f80d146012 | |||
| 1cb2cf3d54 | |||
| 97250d10b7 | |||
| 15979874ce | |||
| 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 | |||
| c6ac974459 |
2
.vscode/launch.json
vendored
2
.vscode/launch.json
vendored
@@ -7,7 +7,7 @@
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "npm: start",
|
||||
"url": "http://localhost:4200/"
|
||||
"url": "http://localhost:4300/"
|
||||
},
|
||||
{
|
||||
"name": "ng test",
|
||||
|
||||
20
angular.json
20
angular.json
@@ -34,7 +34,12 @@
|
||||
"server": "src/main.server.ts",
|
||||
"outputMode": "server",
|
||||
"security": {
|
||||
"allowedHosts": ["localhost", "127.0.0.1"]
|
||||
"allowedHosts": [
|
||||
"localhost",
|
||||
"localhost:4300",
|
||||
"127.0.0.1",
|
||||
"127.0.0.1:4300"
|
||||
]
|
||||
},
|
||||
"ssr": {
|
||||
"entry": "src/server.ts"
|
||||
@@ -64,7 +69,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 +90,9 @@
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular/build:dev-server",
|
||||
"options": {
|
||||
"port": 4300
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"buildTarget": "shopit-front:build:production"
|
||||
@@ -93,7 +107,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 |
28
src/app/app.config.spec.ts
Normal file
28
src/app/app.config.spec.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { HttpRequest } from '@angular/common/http';
|
||||
|
||||
import { isStoreCatalogRequest } from './app.config';
|
||||
|
||||
describe('isStoreCatalogRequest', () => {
|
||||
it.each([
|
||||
'http://localhost:8000/api/tenants/demo/catalog',
|
||||
'http://localhost:8000/api/tenants/demo/catalog?currency=ARS',
|
||||
'http://localhost:8000/api/tenants/demo/catalog/featured-groups/7/items?page=2',
|
||||
'http://localhost:8000/api/tenants/demo/catalog-items?q=remera&page=1',
|
||||
'http://localhost:8000/api/tenants/demo/catalog-items/42?variant_id=3',
|
||||
])('includes GET %s in the hydration transfer cache', (url) => {
|
||||
expect(isStoreCatalogRequest(new HttpRequest('GET', url))).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['POST', 'http://localhost:8000/api/tenants/demo/catalog-items'],
|
||||
['GET', 'http://localhost:8000/api/tenants/demo/productos'],
|
||||
['GET', 'http://localhost:8000/api/tenants/demo/categories/7'],
|
||||
['GET', 'http://localhost:8000/api/tenants/demo/catalog-items/42/variant-options'],
|
||||
['GET', 'http://localhost:8000/api/tenants/demo/catalogue'],
|
||||
])('excludes %s %s from the hydration transfer cache', (method, url) => {
|
||||
const request =
|
||||
method === 'GET' ? new HttpRequest('GET', url) : new HttpRequest('POST', url, null);
|
||||
|
||||
expect(isStoreCatalogRequest(request)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -13,10 +13,12 @@ import { authInterceptor } from './core/services/auth/auth.interceptor';
|
||||
import { globalLoadingInterceptor } from './core/services/global-loading/global-loading.interceptor';
|
||||
import { tenantBootstrap } from './core/services/tenant-bootstrap';
|
||||
|
||||
function isStoreCatalogRequest(request: HttpRequest<unknown>): boolean {
|
||||
export function isStoreCatalogRequest(request: HttpRequest<unknown>): boolean {
|
||||
return (
|
||||
request.method === 'GET' &&
|
||||
/\/api\/tenants\/[^/]+\/productos(?:\/\d+)?(?:\?|$)/.test(request.urlWithParams)
|
||||
/\/api\/tenants\/[^/?#]+\/(?:catalog(?:\/featured-groups\/\d+\/items)?|catalog-items(?:\/\d+)?)\/?(?:[?#]|$)/.test(
|
||||
request.urlWithParams,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -233,6 +233,19 @@ describe('app routes', () => {
|
||||
expect(compiled.textContent).toContain('No encontramos una tienda para este dominio');
|
||||
});
|
||||
|
||||
it('renders the tenant not found screen at / without redirecting to itself', async () => {
|
||||
const { fixture, router } = await renderAppAt(
|
||||
'/',
|
||||
createTenantServiceStub('not-found', null),
|
||||
createAuthServiceStub()
|
||||
);
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
|
||||
expect(router.url).toBe('/');
|
||||
expect(compiled.querySelector('.tenant-status')).not.toBeNull();
|
||||
expect(compiled.textContent).toContain('No encontramos una tienda para este dominio');
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users from /checkout to /login', async () => {
|
||||
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false));
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
76
src/app/core/guards/menu.guard.spec.ts
Normal file
76
src/app/core/guards/menu.guard.spec.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter, Router, UrlTree } from '@angular/router';
|
||||
|
||||
import { Tenant } from '../services/tenant.interface';
|
||||
import { TenantService } from '../services/tenant.service';
|
||||
import { hasMenuGuard } from './menu.guard';
|
||||
|
||||
const tenant: Tenant = {
|
||||
id: 1,
|
||||
codigo: 'test',
|
||||
nombre: 'Test Tenant',
|
||||
dominio: 'localhost',
|
||||
primary_color: '#6376F3',
|
||||
secondary_color: '#A0A0A0',
|
||||
danger_color: '#FF8888',
|
||||
success_color: '#198754',
|
||||
header_bg_color: '#313131',
|
||||
footer_bg_color: '#313131',
|
||||
header_logo: 'https://example.com/header.png',
|
||||
footer_logo: 'https://example.com/footer.png',
|
||||
categories: [],
|
||||
menues: [
|
||||
{
|
||||
id: 1,
|
||||
code: 'index',
|
||||
label: 'Inicio',
|
||||
parent_menu_code: null,
|
||||
content_type: 'dynamic',
|
||||
route: '/',
|
||||
submenues: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function runGuard(menuCode: string, url: string, currentTenant: Tenant | null) {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideRouter([]),
|
||||
{
|
||||
provide: TenantService,
|
||||
useValue: { tenant: () => currentTenant },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return TestBed.runInInjectionContext(() =>
|
||||
hasMenuGuard(menuCode)(null as never, { url } as never),
|
||||
);
|
||||
}
|
||||
|
||||
describe('hasMenuGuard', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('allows a route exposed by the tenant menu', () => {
|
||||
expect(runGuard('index', '/', tenant)).toBe(true);
|
||||
});
|
||||
|
||||
it('cancels navigation when the tenant is missing', () => {
|
||||
expect(runGuard('index', '/', null)).toBe(false);
|
||||
});
|
||||
|
||||
it('redirects a missing menu route to the store root', () => {
|
||||
const result = runGuard('checkout', '/checkout', tenant);
|
||||
|
||||
expect(result instanceof UrlTree).toBe(true);
|
||||
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/');
|
||||
});
|
||||
|
||||
it('allows the store root when its menu is missing to avoid a self-redirect', () => {
|
||||
const tenantWithoutMenus = { ...tenant, menues: [] };
|
||||
|
||||
expect(runGuard('index', '/', tenantWithoutMenus)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -4,19 +4,19 @@ import { findMenu } from '../services/menu.utils';
|
||||
import { TenantService } from '../services/tenant.service';
|
||||
|
||||
export const hasMenuGuard = (menuCode: string): CanActivateFn => {
|
||||
return () => {
|
||||
return (_route, state) => {
|
||||
const tenantService = inject(TenantService);
|
||||
const router = inject(Router);
|
||||
|
||||
const tenant = tenantService.tenant();
|
||||
|
||||
if (!tenant) {
|
||||
return router.createUrlTree(['/']);
|
||||
return false;
|
||||
}
|
||||
|
||||
const hasMenu = findMenu(tenant.menues ?? [], menuCode) !== undefined;
|
||||
|
||||
if (hasMenu) {
|
||||
if (hasMenu || state.url === '/') {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -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,7 +117,10 @@
|
||||
/>
|
||||
|
||||
@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">
|
||||
<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()"
|
||||
@@ -117,15 +129,17 @@
|
||||
<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,7 +21,7 @@
|
||||
|
||||
.store-layout__cart-dropdown {
|
||||
position: absolute;
|
||||
top: 76px;
|
||||
top: 100px;
|
||||
right: calc((100% - 1320px) / 2 + 1.5rem);
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
@@ -29,7 +29,7 @@
|
||||
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;
|
||||
|
||||
@@ -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();
|
||||
@@ -532,10 +571,9 @@ describe('StoreLayoutComponent', () => {
|
||||
precio_unitario: '100.00',
|
||||
catalog_item_id: 1,
|
||||
variant_id: null,
|
||||
product: {
|
||||
nombre: 'Producto',
|
||||
imagen: null,
|
||||
},
|
||||
nombre: 'Producto',
|
||||
imagen: null,
|
||||
variant: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -585,10 +623,9 @@ describe('StoreLayoutComponent', () => {
|
||||
precio_unitario: '100.00',
|
||||
catalog_item_id: 1,
|
||||
variant_id: null,
|
||||
product: {
|
||||
nombre: 'Producto',
|
||||
imagen: null,
|
||||
},
|
||||
nombre: 'Producto',
|
||||
imagen: null,
|
||||
variant: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -6,13 +6,12 @@ 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';
|
||||
import { ToastService } from '../../services/toast.service';
|
||||
import { Category } from '../../services/tenant.interface';
|
||||
import { VariantAttributeValue } from '../../services/catalog/catalog.interface';
|
||||
|
||||
@Component({
|
||||
selector: 'app-store-layout',
|
||||
@@ -36,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();
|
||||
@@ -53,7 +53,7 @@ export class StoreLayoutComponent implements OnInit {
|
||||
});
|
||||
|
||||
private mapCartItemToMock(item: CartItem): CartItemMock {
|
||||
const fullName = item.product?.nombre ?? '';
|
||||
const fullName = item.nombre ?? '';
|
||||
let product = fullName;
|
||||
let attributes: { label: string; value: string }[] = [];
|
||||
|
||||
@@ -70,24 +70,18 @@ export class StoreLayoutComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
const variants = (item.product?.variants ?? []).map((variant) => ({
|
||||
value: variant.id,
|
||||
values: variant.values,
|
||||
}));
|
||||
const selectedVariant = item.product?.variants?.find(
|
||||
(variant) => variant.id === item.variant_id,
|
||||
);
|
||||
const selectedVariant = item.variant;
|
||||
|
||||
if (selectedVariant) {
|
||||
attributes = Object.entries(selectedVariant.values).map(([label, value]) => ({
|
||||
label: this.formatAttributeLabel(label),
|
||||
value: this.variantAttributeLabel(value),
|
||||
value: this.formatAttributeValue(value),
|
||||
}));
|
||||
}
|
||||
|
||||
return {
|
||||
cartItemId: item.id,
|
||||
imageUrl: item.product?.imagen ?? null,
|
||||
imageUrl: item.imagen,
|
||||
product,
|
||||
originalPrice: null,
|
||||
discountedPrice: parseFloat(item.precio_unitario),
|
||||
@@ -95,7 +89,6 @@ export class StoreLayoutComponent implements OnInit {
|
||||
attributes,
|
||||
quantity: item.cantidad,
|
||||
variantId: item.variant_id,
|
||||
variants,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -104,12 +97,9 @@ export class StoreLayoutComponent implements OnInit {
|
||||
return label.charAt(0).toUpperCase() + label.slice(1);
|
||||
}
|
||||
|
||||
private variantAttributeLabel(value: VariantAttributeValue): string {
|
||||
if (typeof value === 'string') return value;
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => (typeof item === 'string' ? item : item.label)).join(', ');
|
||||
}
|
||||
return value.label;
|
||||
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();
|
||||
|
||||
@@ -2,8 +2,10 @@ import { PLATFORM_ID, TransferState } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TimeoutError } from 'rxjs';
|
||||
|
||||
import { environment } from '../../../../environments/environment';
|
||||
import { BOOTSTRAP_REQUEST_TIMEOUT_MS } from '../bootstrap-request-timeout';
|
||||
import { AuthService } from './auth.service';
|
||||
import { CookieService } from '../cookie/cookie.service';
|
||||
import { TenantService } from '../tenant.service';
|
||||
@@ -72,13 +74,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 +154,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,11 +178,48 @@ 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();
|
||||
});
|
||||
|
||||
it('propagates a /me timeout without clearing the local session', async () => {
|
||||
cookieStore['shopit.front.auth.token'] = 'valid-token';
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
AuthService,
|
||||
{ provide: CookieService, useValue: createCookieServiceStub() },
|
||||
{ provide: BOOTSTRAP_REQUEST_TIMEOUT_MS, useValue: 25 },
|
||||
TransferState,
|
||||
],
|
||||
});
|
||||
|
||||
const service = TestBed.inject(AuthService);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
const bootstrapPromise = service.bootstrap();
|
||||
const rejection = expect(bootstrapPromise).rejects.toBeInstanceOf(TimeoutError);
|
||||
const request = httpController.expectOne(`${environment.url}me`);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
await rejection;
|
||||
|
||||
expect(request.cancelled).toBe(true);
|
||||
expect(service.user()).toBeNull();
|
||||
expect(service.token()).toBe('valid-token');
|
||||
expect(cookieStore['shopit.front.auth.token']).toBe('valid-token');
|
||||
|
||||
httpController.verify();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('registers without creating a session', () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
@@ -384,7 +423,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();
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import { DOCUMENT } from '@angular/common';
|
||||
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
|
||||
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
|
||||
import { computed, inject, Injectable, PLATFORM_ID, signal, TransferState, makeStateKey } from '@angular/core';
|
||||
import { firstValueFrom, map, Observable, of, tap } from 'rxjs';
|
||||
import { firstValueFrom, map, Observable, of, tap, timeout } from 'rxjs';
|
||||
|
||||
import { environment } from '../../../../environments/environment';
|
||||
import { BaseApiService } from '../base-api.service';
|
||||
@@ -20,8 +20,9 @@ import {
|
||||
} from './auth.interfaces';
|
||||
import { CookieService } from '../cookie/cookie.service';
|
||||
import { TenantService } from '../tenant.service';
|
||||
import { BOOTSTRAP_REQUEST_TIMEOUT_MS } from '../bootstrap-request-timeout';
|
||||
|
||||
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({
|
||||
@@ -33,6 +34,7 @@ export class AuthService extends BaseApiService {
|
||||
private readonly cookieService = inject(CookieService);
|
||||
private readonly transferState = inject(TransferState);
|
||||
private readonly tenantService = inject(TenantService);
|
||||
private readonly bootstrapRequestTimeoutMs = inject(BOOTSTRAP_REQUEST_TIMEOUT_MS);
|
||||
|
||||
private readonly userState = signal<AuthUser | null>(null);
|
||||
private readonly tokenState = signal<string | null>(null);
|
||||
@@ -175,7 +177,9 @@ export class AuthService extends BaseApiService {
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await firstValueFrom(this.loadCurrentUser());
|
||||
const user = await firstValueFrom(
|
||||
this.loadCurrentUser().pipe(timeout(this.bootstrapRequestTimeoutMs)),
|
||||
);
|
||||
|
||||
if (isPlatformServer(this.platformId)) {
|
||||
this.transferState.set(AUTH_USER_SSR_STATE_KEY, user);
|
||||
|
||||
9
src/app/core/services/bootstrap-request-timeout.ts
Normal file
9
src/app/core/services/bootstrap-request-timeout.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { InjectionToken } from '@angular/core';
|
||||
|
||||
export const BOOTSTRAP_REQUEST_TIMEOUT_MS = new InjectionToken<number>(
|
||||
'BOOTSTRAP_REQUEST_TIMEOUT_MS',
|
||||
{
|
||||
providedIn: 'root',
|
||||
factory: () => 10_000,
|
||||
},
|
||||
);
|
||||
@@ -1,16 +1,18 @@
|
||||
import { VariantAttributeValue } from '../catalog/catalog.interface';
|
||||
|
||||
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, VariantAttributeValue>;
|
||||
values: Record<string, CartItemVariantValue>;
|
||||
}
|
||||
|
||||
export interface CartItem {
|
||||
@@ -19,7 +21,9 @@ export interface CartItem {
|
||||
precio_unitario: string;
|
||||
catalog_item_id: number;
|
||||
variant_id: number | null;
|
||||
product: CartItemProduct | null;
|
||||
nombre: string | null;
|
||||
imagen: string | null;
|
||||
variant: CartItemVariant | null;
|
||||
}
|
||||
|
||||
export interface Cart {
|
||||
|
||||
@@ -24,9 +24,13 @@ describe('CartService', () => {
|
||||
precio_unitario: '10.00',
|
||||
catalog_item_id: 5,
|
||||
variant_id: 10,
|
||||
product: {
|
||||
nombre: 'Test Product (Size: M)',
|
||||
imagen: null,
|
||||
nombre: 'Test Product (Size: M)',
|
||||
imagen: null,
|
||||
variant: {
|
||||
id: 10,
|
||||
precio: '10.00',
|
||||
stock_tecnico: 1,
|
||||
values: { size: 'M' },
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -18,6 +18,7 @@ export interface Product {
|
||||
|
||||
export interface ProductAttributeOption {
|
||||
id: number;
|
||||
validity_time_id?: number | null;
|
||||
value: string;
|
||||
label: string;
|
||||
sort_order: number;
|
||||
@@ -40,6 +41,7 @@ export interface ProductAttribute {
|
||||
nombre: string;
|
||||
is_required: boolean;
|
||||
allow_multi_select?: boolean;
|
||||
show_in_selector?: boolean;
|
||||
metadata_schema: Record<string, unknown> | null;
|
||||
type: ProductAttributeType;
|
||||
options: ProductAttributeOption[];
|
||||
@@ -47,16 +49,15 @@ export interface ProductAttribute {
|
||||
|
||||
export type InventoryPolicy = 'tracked' | 'unlimited';
|
||||
|
||||
export interface VariantAttributeOptionValue {
|
||||
export interface CatalogVariantOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export type VariantAttributeValue =
|
||||
| VariantAttributeOptionValue
|
||||
| VariantAttributeOptionValue[]
|
||||
export type CatalogVariantValue =
|
||||
| string
|
||||
| string[];
|
||||
| CatalogVariantOption
|
||||
| Array<string | CatalogVariantOption>;
|
||||
|
||||
export interface CatalogItemVariant {
|
||||
id: number;
|
||||
@@ -70,7 +71,7 @@ export interface CatalogItemVariant {
|
||||
maximum_use_date?: string | null;
|
||||
effective_minimum_use_date?: string | null;
|
||||
effective_maximum_use_date?: string | null;
|
||||
values: Record<string, VariantAttributeValue>;
|
||||
values: Record<string, string | string[]>;
|
||||
}
|
||||
|
||||
export interface SelectedCatalogItemVariant extends CatalogItemVariant {
|
||||
@@ -101,15 +102,40 @@ 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, VariantAttributeValue>;
|
||||
values: Record<string, CatalogVariantValue>;
|
||||
}
|
||||
|
||||
export interface CatalogVariantOptionsResponse {
|
||||
variants: CatalogFeaturedItemVariant[];
|
||||
selectors: CatalogVariantSelector[];
|
||||
selected_values: Record<string, string | string[]>;
|
||||
resolved_variant: CatalogFeaturedItemVariant | null;
|
||||
valid: boolean;
|
||||
available_variant_count: number;
|
||||
matching_variant_count: number;
|
||||
price_range: {
|
||||
minimum: string;
|
||||
maximum: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CatalogVariantSelector {
|
||||
key: string;
|
||||
label: string;
|
||||
options: CatalogVariantValue[];
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface CatalogFeaturedItem {
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
CatalogFeaturedItem,
|
||||
CatalogFeaturedItems,
|
||||
CatalogItemDetail,
|
||||
CatalogVariantOptionsResponse,
|
||||
CategoryItemsResponse,
|
||||
Product,
|
||||
} from './catalog.interface';
|
||||
@@ -74,10 +75,7 @@ export class CatalogService extends BaseApiService {
|
||||
);
|
||||
}
|
||||
|
||||
getCatalogItem(
|
||||
id: number,
|
||||
variantId?: number,
|
||||
): Observable<CatalogItemDetail> {
|
||||
getCatalogItem(id: number, variantId?: number): Observable<CatalogItemDetail> {
|
||||
let params = new HttpParams();
|
||||
if (variantId) {
|
||||
params = params.set('variant_id', variantId);
|
||||
@@ -90,6 +88,20 @@ export class CatalogService extends BaseApiService {
|
||||
.pipe(map((response) => response.data));
|
||||
}
|
||||
|
||||
getVariantOptions(
|
||||
catalogItemId: number,
|
||||
payload: {
|
||||
selected_values: Record<string, string | string[]>;
|
||||
cart_item_id?: number | null;
|
||||
},
|
||||
): Observable<CatalogVariantOptionsResponse> {
|
||||
return this.http
|
||||
.post<
|
||||
ApiResponse<CatalogVariantOptionsResponse>
|
||||
>(`${this.tenantApiUrl}/catalog-items/${catalogItemId}/variant-options`, payload, { withCredentials: true })
|
||||
.pipe(map((response) => response.data));
|
||||
}
|
||||
|
||||
private buildHttpParams(params?: ApiPaginationQueryParams): HttpParams {
|
||||
if (!params) {
|
||||
return new HttpParams();
|
||||
|
||||
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 {
|
||||
@@ -181,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`,
|
||||
@@ -222,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`,
|
||||
@@ -249,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> {
|
||||
|
||||
@@ -20,13 +20,18 @@ export interface WebsiteType {
|
||||
}
|
||||
|
||||
export interface HeroConfig {
|
||||
background_image_id?: string | null;
|
||||
background_image_id?: string | ResponsiveImage | null;
|
||||
title_html?: string | null;
|
||||
description_html?: string | null;
|
||||
button_text?: string | null;
|
||||
button_href?: string | null;
|
||||
}
|
||||
|
||||
export interface ResponsiveImage {
|
||||
desktop: string;
|
||||
mobile: string;
|
||||
}
|
||||
|
||||
export interface AdditionalInfoConfig {
|
||||
description?: string | null;
|
||||
}
|
||||
@@ -96,6 +101,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;
|
||||
@@ -104,6 +111,8 @@ 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;
|
||||
@@ -111,9 +120,12 @@ export interface Tenant {
|
||||
event?: TenantEvent | null;
|
||||
selected_bank_account_id?: number | null;
|
||||
selected_bank_account?: BankAccount | 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;
|
||||
display_categories?: boolean;
|
||||
display_seach_bar?: boolean;
|
||||
display_cart?: boolean;
|
||||
social_media?: SocialMedia[];
|
||||
menues?: Menu[];
|
||||
categories: Category[];
|
||||
|
||||
@@ -2,8 +2,10 @@ import { PLATFORM_ID, REQUEST, RESPONSE_INIT, TransferState } from '@angular/cor
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TimeoutError } from 'rxjs';
|
||||
|
||||
import { environment } from '../../../environments/environment';
|
||||
import { BOOTSTRAP_REQUEST_TIMEOUT_MS } from './bootstrap-request-timeout';
|
||||
import { Tenant, TenantBootstrapResponse } from './tenant.interface';
|
||||
import { TENANT_SSR_STATE_KEY } from './tenant-ssr-cache.store';
|
||||
import { TenantService } from './tenant.service';
|
||||
@@ -29,15 +31,15 @@ const tenant: Tenant = {
|
||||
{
|
||||
id: 2,
|
||||
nombre: 'Manga corta',
|
||||
subcategories: []
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
subcategories: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const tenantResponse: TenantBootstrapResponse = {
|
||||
data: tenant
|
||||
data: tenant,
|
||||
};
|
||||
|
||||
describe('TenantService', () => {
|
||||
@@ -51,14 +53,16 @@ describe('TenantService', () => {
|
||||
|
||||
it('requests the tenant bootstrap endpoint using the current hostname and stores the response', async () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService]
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService],
|
||||
});
|
||||
|
||||
const service = TestBed.inject(TenantService);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
const bootstrapPromise = service.bootstrap();
|
||||
const request = httpController.expectOne(`${environment.url}tenants/bootstrap/localhost`);
|
||||
const request = httpController.expectOne(
|
||||
`${environment.url}tenants/bootstrap?dominio=localhost&path=/`,
|
||||
);
|
||||
|
||||
expect(request.request.method).toBe('GET');
|
||||
|
||||
@@ -74,7 +78,7 @@ describe('TenantService', () => {
|
||||
|
||||
it('hydrates the tenant from TransferState without performing HTTP on the browser', async () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService]
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService],
|
||||
});
|
||||
|
||||
const service = TestBed.inject(TenantService);
|
||||
@@ -83,7 +87,7 @@ describe('TenantService', () => {
|
||||
|
||||
transferState.set(TENANT_SSR_STATE_KEY, {
|
||||
status: 'ready',
|
||||
tenant
|
||||
tenant,
|
||||
});
|
||||
|
||||
await expect(service.bootstrap()).resolves.toBeUndefined();
|
||||
@@ -109,12 +113,12 @@ describe('TenantService', () => {
|
||||
useValue: new Request('https://internal.example/render', {
|
||||
headers: {
|
||||
'x-forwarded-host': 'STORE.EXAMPLE.COM:443, proxy.internal',
|
||||
host: 'ignored.example.com'
|
||||
}
|
||||
})
|
||||
host: 'ignored.example.com',
|
||||
},
|
||||
}),
|
||||
},
|
||||
{ provide: RESPONSE_INIT, useValue: responseInit }
|
||||
]
|
||||
{ provide: RESPONSE_INIT, useValue: responseInit },
|
||||
],
|
||||
});
|
||||
|
||||
const service = TestBed.inject(TenantService);
|
||||
@@ -122,7 +126,9 @@ describe('TenantService', () => {
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
const bootstrapPromise = service.bootstrap();
|
||||
const request = httpController.expectOne(`${environment.url}tenants/bootstrap/store.example.com`);
|
||||
const request = httpController.expectOne(
|
||||
`${environment.url}tenants/bootstrap?dominio=store.example.com&path=/render`,
|
||||
);
|
||||
|
||||
request.flush(tenantResponse);
|
||||
|
||||
@@ -131,7 +137,7 @@ describe('TenantService', () => {
|
||||
expect(service.tenant()).toEqual(tenant);
|
||||
expect(transferState.get(TENANT_SSR_STATE_KEY, null)).toEqual({
|
||||
status: 'ready',
|
||||
tenant
|
||||
tenant,
|
||||
});
|
||||
expect(responseInit.status).toBeUndefined();
|
||||
|
||||
@@ -151,12 +157,12 @@ describe('TenantService', () => {
|
||||
provide: REQUEST,
|
||||
useValue: new Request('https://internal.example/render', {
|
||||
headers: {
|
||||
host: 'missing.example.com:8443'
|
||||
}
|
||||
})
|
||||
host: 'missing.example.com:8443',
|
||||
},
|
||||
}),
|
||||
},
|
||||
{ provide: RESPONSE_INIT, useValue: responseInit }
|
||||
]
|
||||
{ provide: RESPONSE_INIT, useValue: responseInit },
|
||||
],
|
||||
});
|
||||
|
||||
const service = TestBed.inject(TenantService);
|
||||
@@ -164,7 +170,9 @@ describe('TenantService', () => {
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
const bootstrapPromise = service.bootstrap();
|
||||
const request = httpController.expectOne(`${environment.url}tenants/bootstrap/missing.example.com`);
|
||||
const request = httpController.expectOne(
|
||||
`${environment.url}tenants/bootstrap?dominio=missing.example.com&path=/render`,
|
||||
);
|
||||
|
||||
request.flush({ message: 'Not Found' }, { status: 404, statusText: 'Not Found' });
|
||||
|
||||
@@ -173,7 +181,7 @@ describe('TenantService', () => {
|
||||
expect(service.tenant()).toBeNull();
|
||||
expect(service.getTenant()).toBeNull();
|
||||
expect(transferState.get(TENANT_SSR_STATE_KEY, null)).toEqual({
|
||||
status: 'not-found'
|
||||
status: 'not-found',
|
||||
});
|
||||
expect(responseInit.status).toBe(404);
|
||||
|
||||
@@ -182,14 +190,16 @@ describe('TenantService', () => {
|
||||
|
||||
it('rejects when the bootstrap response does not contain tenant data', async () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService]
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService],
|
||||
});
|
||||
|
||||
const service = TestBed.inject(TenantService);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
const bootstrapPromise = service.bootstrap();
|
||||
const request = httpController.expectOne(`${environment.url}tenants/bootstrap/localhost`);
|
||||
const request = httpController.expectOne(
|
||||
`${environment.url}tenants/bootstrap?dominio=localhost&path=/`,
|
||||
);
|
||||
|
||||
request.flush({});
|
||||
|
||||
@@ -213,19 +223,21 @@ describe('TenantService', () => {
|
||||
provide: REQUEST,
|
||||
useValue: new Request('https://internal.example/render', {
|
||||
headers: {
|
||||
host: 'broken.example.com'
|
||||
}
|
||||
})
|
||||
host: 'broken.example.com',
|
||||
},
|
||||
}),
|
||||
},
|
||||
{ provide: RESPONSE_INIT, useValue: responseInit }
|
||||
]
|
||||
{ provide: RESPONSE_INIT, useValue: responseInit },
|
||||
],
|
||||
});
|
||||
|
||||
const service = TestBed.inject(TenantService);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
const bootstrapPromise = service.bootstrap();
|
||||
const request = httpController.expectOne(`${environment.url}tenants/bootstrap/broken.example.com`);
|
||||
const request = httpController.expectOne(
|
||||
`${environment.url}tenants/bootstrap?dominio=broken.example.com&path=/render`,
|
||||
);
|
||||
|
||||
request.flush({ message: 'Boom' }, { status: 500, statusText: 'Server Error' });
|
||||
|
||||
@@ -235,4 +247,39 @@ describe('TenantService', () => {
|
||||
|
||||
httpController.verify();
|
||||
});
|
||||
|
||||
it('rejects and cancels a tenant bootstrap request that exceeds the configured timeout', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
TenantService,
|
||||
{ provide: BOOTSTRAP_REQUEST_TIMEOUT_MS, useValue: 25 },
|
||||
],
|
||||
});
|
||||
|
||||
const service = TestBed.inject(TenantService);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
const bootstrapPromise = service.bootstrap();
|
||||
const rejection = expect(bootstrapPromise).rejects.toBeInstanceOf(TimeoutError);
|
||||
const request = httpController.expectOne(
|
||||
`${environment.url}tenants/bootstrap?dominio=localhost&path=/`,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
await rejection;
|
||||
|
||||
expect(request.cancelled).toBe(true);
|
||||
expect(service.status()).toBe('idle');
|
||||
expect(service.tenant()).toBeNull();
|
||||
|
||||
httpController.verify();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,22 +7,23 @@ import {
|
||||
REQUEST,
|
||||
RESPONSE_INIT,
|
||||
signal,
|
||||
TransferState
|
||||
TransferState,
|
||||
} from '@angular/core';
|
||||
import { IS_DISCOVERING_ROUTES } from '@angular/ssr';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { firstValueFrom, timeout } from 'rxjs';
|
||||
|
||||
import { environment } from '../../../environments/environment';
|
||||
import { BaseApiService } from './base-api.service';
|
||||
import { BOOTSTRAP_REQUEST_TIMEOUT_MS } from './bootstrap-request-timeout';
|
||||
import { Tenant, TenantBootstrapResponse } from './tenant.interface';
|
||||
import {
|
||||
TENANT_SSR_STATE_KEY,
|
||||
TenantBootstrapStatus,
|
||||
TenantSsrState
|
||||
TenantSsrState,
|
||||
} from './tenant-ssr-cache.store';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class TenantService extends BaseApiService {
|
||||
private readonly platformId = inject(PLATFORM_ID);
|
||||
@@ -30,6 +31,7 @@ export class TenantService extends BaseApiService {
|
||||
private readonly responseInit = inject(RESPONSE_INIT, { optional: true });
|
||||
private readonly transferState = inject(TransferState);
|
||||
private readonly isDiscoveringRoutes = inject(IS_DISCOVERING_ROUTES, { optional: true }) ?? false;
|
||||
private readonly bootstrapRequestTimeoutMs = inject(BOOTSTRAP_REQUEST_TIMEOUT_MS);
|
||||
private readonly tenantState = signal<Tenant | null>(null);
|
||||
private readonly statusState = signal<TenantBootstrapStatus>('idle');
|
||||
|
||||
@@ -48,7 +50,6 @@ export class TenantService extends BaseApiService {
|
||||
return `${environment.url}tenants/${tenant.codigo}`;
|
||||
}
|
||||
|
||||
|
||||
async bootstrap(): Promise<void> {
|
||||
if (this.statusState() !== 'idle') {
|
||||
return;
|
||||
@@ -69,13 +70,18 @@ export class TenantService extends BaseApiService {
|
||||
return;
|
||||
}
|
||||
|
||||
const domain = this.resolveDomain();
|
||||
const { domain, path } = this.resolveRequestContext();
|
||||
|
||||
try {
|
||||
const response = await firstValueFrom(
|
||||
this.http.get<TenantBootstrapResponse>(
|
||||
`${environment.url}tenants/bootstrap/${domain}`
|
||||
)
|
||||
this.http
|
||||
.get<TenantBootstrapResponse>(`${environment.url}tenants/bootstrap`, {
|
||||
params: {
|
||||
dominio: domain,
|
||||
path,
|
||||
},
|
||||
})
|
||||
.pipe(timeout(this.bootstrapRequestTimeoutMs)),
|
||||
);
|
||||
|
||||
if (!response?.data) {
|
||||
@@ -85,7 +91,7 @@ export class TenantService extends BaseApiService {
|
||||
this.setReady(response.data);
|
||||
this.persistSsrState({
|
||||
status: 'ready',
|
||||
tenant: response.data
|
||||
tenant: response.data,
|
||||
});
|
||||
} catch (error) {
|
||||
if (this.isNotFoundError(error)) {
|
||||
@@ -103,7 +109,7 @@ export class TenantService extends BaseApiService {
|
||||
}
|
||||
}
|
||||
|
||||
private resolveDomain(): string {
|
||||
private resolveRequestContext(): { domain: string; path: string } {
|
||||
if (isPlatformBrowser(this.platformId)) {
|
||||
const domain = window.location.hostname;
|
||||
|
||||
@@ -111,7 +117,10 @@ export class TenantService extends BaseApiService {
|
||||
throw new Error('Tenant bootstrap could not resolve the current domain.');
|
||||
}
|
||||
|
||||
return this.normalizeHost(domain);
|
||||
return {
|
||||
domain: this.normalizeHost(domain),
|
||||
path: this.normalizePath(window.location.pathname),
|
||||
};
|
||||
}
|
||||
|
||||
const requestHost =
|
||||
@@ -123,7 +132,14 @@ export class TenantService extends BaseApiService {
|
||||
throw new Error('Tenant bootstrap could not resolve the current domain.');
|
||||
}
|
||||
|
||||
return this.normalizeHost(requestHost);
|
||||
const forwardedPath =
|
||||
this.request?.headers.get('x-forwarded-uri') ?? this.request?.headers.get('x-original-uri');
|
||||
const requestPath = forwardedPath ?? (this.request ? new URL(this.request.url).pathname : '/');
|
||||
|
||||
return {
|
||||
domain: this.normalizeHost(requestHost),
|
||||
path: this.normalizePath(requestPath),
|
||||
};
|
||||
}
|
||||
|
||||
private normalizeHost(host: string): string {
|
||||
@@ -145,6 +161,16 @@ export class TenantService extends BaseApiService {
|
||||
return normalizedHost.replace(/:\d+$/, '');
|
||||
}
|
||||
|
||||
private normalizePath(path: string): string {
|
||||
const pathname = path.split(/[?#]/, 1)[0]?.trim() ?? '';
|
||||
|
||||
if (!pathname || pathname === '/') {
|
||||
return '/';
|
||||
}
|
||||
|
||||
return `/${pathname.replace(/^\/+|\/+$/g, '')}`;
|
||||
}
|
||||
|
||||
private applyState(state: TenantSsrState): void {
|
||||
if (state.status === 'ready') {
|
||||
this.setReady(state.tenant);
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
export interface TimeWindowValidityTime {
|
||||
id: number;
|
||||
type: 'time_window';
|
||||
is_valid: boolean;
|
||||
start_time?: string;
|
||||
end_time?: string;
|
||||
}
|
||||
|
||||
export interface FixedWindowValidityTime {
|
||||
id: number;
|
||||
type: 'fixed_window';
|
||||
is_valid: boolean;
|
||||
fixed_starts_at?: string;
|
||||
fixed_expires_at?: string;
|
||||
}
|
||||
|
||||
export type ValidityTime = TimeWindowValidityTime | FixedWindowValidityTime;
|
||||
@@ -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
|
||||
[productId]="1"
|
||||
[title]="testTicketSelectorProduct.title"
|
||||
[description]="testTicketSelectorProduct.description"
|
||||
[price]="testTicketSelectorProduct.price"
|
||||
[imageUrl]="testTicketSelectorProduct.imageUrl"
|
||||
(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,9 +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: [
|
||||
{ value: '10-oct-manana', values: { fecha: '10 de Octubre', turno: 'Mañana' } },
|
||||
{ value: '10-oct-tarde', values: { fecha: '10 de Octubre', turno: 'Tarde' } },
|
||||
{ value: '11-oct-tarde', values: { fecha: '11 de Octubre', turno: 'Tarde' } },
|
||||
{ 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' } },
|
||||
],
|
||||
};
|
||||
|
||||
@@ -216,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,
|
||||
@@ -272,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.codigo) {
|
||||
@for (attribute of visibleAttributes(); track attribute.codigo) {
|
||||
<div class="attribute-selector__row">
|
||||
<span class="attribute-selector__label">{{ attribute.nombre }}:</span>
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -110,4 +110,43 @@ describe('ProductAttributeSelectorComponent', () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
InventoryPolicy,
|
||||
ProductAttribute,
|
||||
ProductAttributeOption,
|
||||
VariantAttributeValue,
|
||||
} from '../../../../core/services/catalog/catalog.interface';
|
||||
|
||||
@Component({
|
||||
@@ -33,12 +32,16 @@ export class ProductAttributeSelectorComponent {
|
||||
|
||||
public variantChange = output<CatalogItemVariant | null>();
|
||||
|
||||
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<string, Record<number, boolean>> = {};
|
||||
|
||||
@@ -104,7 +107,7 @@ export class ProductAttributeSelectorComponent {
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const attributes = this.attributes();
|
||||
const attributes = this.visibleAttributes();
|
||||
const defaultVariant = this.selectedVariant();
|
||||
|
||||
untracked(() => {
|
||||
@@ -115,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);
|
||||
@@ -199,7 +202,7 @@ export class ProductAttributeSelectorComponent {
|
||||
|
||||
private getVariantAttributeValues(
|
||||
attribute: ProductAttribute,
|
||||
variantAttributes: Record<string, VariantAttributeValue>,
|
||||
variantAttributes: Record<string, string | string[]>,
|
||||
): string[] {
|
||||
const normalizedCodigo = this.normalizeText(attribute.codigo);
|
||||
const normalizedNombre = this.normalizeText(attribute.nombre);
|
||||
@@ -208,9 +211,7 @@ export class ProductAttributeSelectorComponent {
|
||||
const normalizedKey = this.normalizeText(key);
|
||||
|
||||
if (normalizedKey === normalizedCodigo || normalizedKey === normalizedNombre) {
|
||||
return (Array.isArray(value) ? value : [value]).map((item) =>
|
||||
this.normalizeText(typeof item === 'string' ? item : item.value),
|
||||
);
|
||||
return (Array.isArray(value) ? value : [value]).map((item) => this.normalizeText(item));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
[layout]="categoryResults.layout"
|
||||
[groupLayout]="paginatedLayout"
|
||||
[items]="categoryResults"
|
||||
[savingProductIds]="savingProductIds()"
|
||||
(buy)="onBuyProduct($event)"
|
||||
(addToCart)="onAddToCart($event)"
|
||||
(pageChange)="onPageChange($event)"
|
||||
|
||||
@@ -9,7 +9,16 @@ import {
|
||||
} from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { catchError, combineLatest, distinctUntilChanged, map, of, switchMap, tap } from 'rxjs';
|
||||
import {
|
||||
catchError,
|
||||
combineLatest,
|
||||
distinctUntilChanged,
|
||||
finalize,
|
||||
map,
|
||||
of,
|
||||
switchMap,
|
||||
tap,
|
||||
} from 'rxjs';
|
||||
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
@@ -52,6 +61,7 @@ export class CategoryItemsPageComponent {
|
||||
protected readonly results = signal<CategoryItemsResponse | null>(null);
|
||||
protected readonly error = signal<string | null>(null);
|
||||
protected readonly creatingDirectPurchase = signal(false);
|
||||
protected readonly savingProductIds = signal<ReadonlySet<number>>(new Set<number>());
|
||||
protected readonly paginatedLayout: CatalogGroupLayout = 'paginated';
|
||||
|
||||
constructor() {
|
||||
@@ -113,7 +123,9 @@ export class CategoryItemsPageComponent {
|
||||
|
||||
if (!this.injector.get(AuthService).user()) {
|
||||
await this.router.navigate(['/login'], {
|
||||
queryParams: { returnUrl: `/producto/${event.product.id}` },
|
||||
queryParams: {
|
||||
returnUrl: event.reservedInCart ? this.router.url : `/producto/${event.product.id}`,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -126,13 +138,25 @@ 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,
|
||||
},
|
||||
});
|
||||
const reservedCartId = event.reservedInCart ? (this.cartService.cart()?.id ?? null) : null;
|
||||
if (event.reservedInCart && reservedCartId === null) {
|
||||
this.toastService.danger('No se pudo identificar el carrito reservado.');
|
||||
return;
|
||||
}
|
||||
const purchase = await this.injector.get(CheckoutService).startCheckout(
|
||||
tenant.codigo,
|
||||
reservedCartId !== null
|
||||
? { cart_id: reservedCartId }
|
||||
: {
|
||||
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) {
|
||||
console.error('Failed to create direct purchase:', error);
|
||||
@@ -143,14 +167,31 @@ export class CategoryItemsPageComponent {
|
||||
}
|
||||
|
||||
protected onAddToCart(event: ProductListCartEvent): void {
|
||||
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).subscribe({
|
||||
next: (response) => {
|
||||
this.toastService.success(response.message || 'Producto agregado al carrito');
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
|
||||
this.toastService.danger(message);
|
||||
},
|
||||
const productId = event.product.id;
|
||||
if (this.savingProductIds().has(productId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.setProductSaving(productId, true);
|
||||
this.cartService
|
||||
.addItem(productId, event.variant ?? null, event.quantity)
|
||||
.pipe(finalize(() => this.setProductSaving(productId, false)))
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
this.toastService.success(response.message || 'Producto agregado al carrito');
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
|
||||
this.toastService.danger(message);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private setProductSaving(productId: number, saving: boolean): void {
|
||||
this.savingProductIds.update((current) => {
|
||||
const updated = new Set(current);
|
||||
saving ? updated.add(productId) : updated.delete(productId);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -63,7 +63,9 @@
|
||||
[disabled]="!selectedVariantAvailable() || variantLoading() || addingToCart()"
|
||||
(click)="addToCart()"
|
||||
>
|
||||
@if (variantLoading() || addingToCart()) {
|
||||
@if (addingToCart()) {
|
||||
Guardando
|
||||
} @else if (variantLoading()) {
|
||||
<div class="spinner-border spinner-border-sm" role="status"></div>
|
||||
} @else {
|
||||
Agregar al carrito
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -480,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 },
|
||||
|
||||
@@ -124,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,
|
||||
@@ -317,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'], {
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
[layout]="productLayout()"
|
||||
[groupLayout]="groupLayout()"
|
||||
[items]="displayItems()"
|
||||
[savingProductIds]="savingProductIds()"
|
||||
(buy)="onBuyProduct($event)"
|
||||
(addToCart)="onAddToCart($event)"
|
||||
(pageChange)="onPageChange($event)"
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { catchError, distinctUntilChanged, map, of, switchMap, tap } from 'rxjs';
|
||||
import { catchError, distinctUntilChanged, finalize, map, of, switchMap, tap } from 'rxjs';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
@@ -58,6 +58,7 @@ export class SearchPageComponent {
|
||||
protected readonly results = signal<ApiPaginatedResponse<CatalogFeaturedItem[]> | null>(null);
|
||||
protected readonly error = signal<string | null>(null);
|
||||
protected readonly creatingDirectPurchase = signal(false);
|
||||
protected readonly savingProductIds = signal<ReadonlySet<number>>(new Set<number>());
|
||||
|
||||
protected readonly productLayout = computed<CatalogProductLayout>(
|
||||
() => this.tenantService.tenant()?.search_product_layout ?? 'column_with_image',
|
||||
@@ -145,7 +146,9 @@ export class SearchPageComponent {
|
||||
|
||||
if (!this.injector.get(AuthService).user()) {
|
||||
await this.router.navigate(['/login'], {
|
||||
queryParams: { returnUrl: `/producto/${event.product.id}` },
|
||||
queryParams: {
|
||||
returnUrl: event.reservedInCart ? this.router.url : `/producto/${event.product.id}`,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -158,13 +161,25 @@ 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,
|
||||
},
|
||||
});
|
||||
const reservedCartId = event.reservedInCart ? (this.cartService.cart()?.id ?? null) : null;
|
||||
if (event.reservedInCart && reservedCartId === null) {
|
||||
this.toastService.danger('No se pudo identificar el carrito reservado.');
|
||||
return;
|
||||
}
|
||||
const purchase = await this.injector.get(CheckoutService).startCheckout(
|
||||
tenant.codigo,
|
||||
reservedCartId !== null
|
||||
? { cart_id: reservedCartId }
|
||||
: {
|
||||
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) {
|
||||
console.error('Failed to create direct purchase:', error);
|
||||
@@ -175,14 +190,31 @@ export class SearchPageComponent {
|
||||
}
|
||||
|
||||
protected onAddToCart(event: ProductListCartEvent): void {
|
||||
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).subscribe({
|
||||
next: (response) => {
|
||||
this.toastService.success(response.message || 'Producto agregado al carrito');
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
|
||||
this.toastService.danger(message);
|
||||
},
|
||||
const productId = event.product.id;
|
||||
if (this.savingProductIds().has(productId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.setProductSaving(productId, true);
|
||||
this.cartService
|
||||
.addItem(productId, event.variant ?? null, event.quantity)
|
||||
.pipe(finalize(() => this.setProductSaving(productId, false)))
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
this.toastService.success(response.message || 'Producto agregado al carrito');
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
|
||||
this.toastService.danger(message);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private setProductSaving(productId: number, saving: boolean): void {
|
||||
this.savingProductIds.update((current) => {
|
||||
const updated = new Set(current);
|
||||
saving ? updated.add(productId) : updated.delete(productId);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,8 @@
|
||||
[items]="group.items"
|
||||
[loading]="isGroupLoading(group.id)"
|
||||
[loadImages]="!hasMainCarouselImages() || mainCarouselReady()"
|
||||
[unavailableVariantIds]="unavailableVariantIds()"
|
||||
[savingProductIds]="savingProductIds()"
|
||||
(buy)="onBuyProduct($event)"
|
||||
(addToCart)="onAddToCart($event)"
|
||||
(pageChange)="onPageChange(group.id, $event)"
|
||||
|
||||
@@ -30,6 +30,13 @@ app-store-section + app-store-section {
|
||||
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);
|
||||
|
||||
@@ -254,9 +254,10 @@ describe('StoreHomePageComponent', () => {
|
||||
const hero = (fixture.nativeElement as HTMLElement).querySelector(
|
||||
'app-hero-banner .hero-banner',
|
||||
) as HTMLElement;
|
||||
const heroImage = hero.querySelector('img');
|
||||
|
||||
expect(hero).not.toBeNull();
|
||||
expect(hero.style.backgroundImage).toContain('https://example.com/hero.jpg');
|
||||
expect(heroImage?.getAttribute('src')).toBe('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');
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { finalize, Subscription } from 'rxjs';
|
||||
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
@@ -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,6 +63,8 @@ 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 unavailableVariantIds = signal<ReadonlySet<number>>(new Set<number>());
|
||||
protected readonly savingProductIds = 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(
|
||||
@@ -165,7 +170,9 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
|
||||
if (!this.injector.get(AuthService).user()) {
|
||||
await this.router.navigate(['/login'], {
|
||||
queryParams: { returnUrl: `/producto/${event.product.id}` },
|
||||
queryParams: {
|
||||
returnUrl: event.reservedInCart ? this.router.url : `/producto/${event.product.id}`,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -178,16 +185,45 @@ 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 reservedCartId = event.reservedInCart ? (this.cartService.cart()?.id ?? null) : null;
|
||||
if (event.reservedInCart && reservedCartId === null) {
|
||||
this.toastService.danger('No se pudo identificar el carrito reservado.');
|
||||
return;
|
||||
}
|
||||
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,
|
||||
reservedCartId !== null ? { cart_id: reservedCartId } : { 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);
|
||||
@@ -195,14 +231,31 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
protected onAddToCart(event: ProductListCartEvent): void {
|
||||
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).subscribe({
|
||||
next: (response) => {
|
||||
this.toastService.success(response.message || 'Producto agregado al carrito');
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
|
||||
this.toastService.danger(message);
|
||||
},
|
||||
const productId = event.product.id;
|
||||
if (this.savingProductIds().has(productId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.setProductSaving(productId, true);
|
||||
this.cartService
|
||||
.addItem(productId, event.variant ?? null, event.quantity)
|
||||
.pipe(finalize(() => this.setProductSaving(productId, false)))
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
this.toastService.success(response.message || 'Producto agregado al carrito');
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
|
||||
this.toastService.danger(message);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private setProductSaving(productId: number, saving: boolean): void {
|
||||
this.savingProductIds.update((current) => {
|
||||
const updated = new Set(current);
|
||||
saving ? updated.add(productId) : updated.delete(productId);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
@@ -120,8 +120,8 @@
|
||||
}
|
||||
|
||||
.cart-item-variant-selector {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.cart-item-remove-btn {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
|
||||
|
||||
<div class="d-flex align-items-center cart-header-actions">
|
||||
@if (!readonly() && allowEditing() && items().length > 0) {
|
||||
@if (!readonly() && editable() && allowEditing() && items().length > 0) {
|
||||
<button
|
||||
class="btn btn-link p-0 border-0 cart-edit-btn"
|
||||
type="button"
|
||||
@@ -48,7 +48,7 @@
|
||||
[selectedVariant]="getItemVariant(item)"
|
||||
[quantity]="getItemQuantity(item)"
|
||||
[readonly]="readonly()"
|
||||
[quantityDisabled]="editingDisabled() || (allowEditing() && !editing())"
|
||||
[quantityDisabled]="!editable() || editingDisabled() || (allowEditing() && !editing())"
|
||||
[showRemove]="allowRemove()"
|
||||
(quantityChange)="onItemQuantityChange(idx, $event)"
|
||||
(variantChange)="onItemVariantChange(idx, $event)"
|
||||
|
||||
@@ -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',
|
||||
});
|
||||
@@ -408,6 +408,54 @@ describe('CartComponent', () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('hides the edit toggle and disables quantity changes when editable is false', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CartComponent],
|
||||
providers: [
|
||||
{
|
||||
provide: CartService,
|
||||
useValue: {
|
||||
cart: signal(null).asReadonly(),
|
||||
updateItemQuantity: vi.fn(),
|
||||
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: 'Producto de prueba',
|
||||
originalPrice: null,
|
||||
discountedPrice: 1000,
|
||||
discountPercentage: null,
|
||||
attributes: [],
|
||||
quantity: 1,
|
||||
},
|
||||
]);
|
||||
fixture.componentRef.setInput('allowEditing', true);
|
||||
fixture.componentRef.setInput('editable', false);
|
||||
const quantityChange = vi.fn();
|
||||
fixture.componentInstance.itemQuantityChange.subscribe(quantityChange);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.debugElement.query(By.css('.cart-edit-btn'))).toBeNull();
|
||||
const cartItem = fixture.debugElement.query(By.css('app-cart-item'));
|
||||
expect(cartItem.componentInstance.quantityDisabled()).toBe(true);
|
||||
|
||||
cartItem.triggerEventHandler('quantityChange', 2);
|
||||
|
||||
expect(quantityChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('persists a variant selected from a cart row', async () => {
|
||||
const updateItemVariant = vi.fn().mockReturnValue(
|
||||
of({
|
||||
@@ -449,8 +497,8 @@ describe('CartComponent', () => {
|
||||
quantity: 2,
|
||||
variantId: 20,
|
||||
variants: [
|
||||
{ value: 20, values: { servicio: 'Almuerzo' } },
|
||||
{ value: 21, values: { servicio: 'Cena' } },
|
||||
{ id: 20, values: { servicio: 'Almuerzo' } },
|
||||
{ id: 21, values: { servicio: 'Cena' } },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -53,6 +53,7 @@ export class CartComponent {
|
||||
readonly total = input<number>(0);
|
||||
readonly backgroundColor = input<string>('#ffffff');
|
||||
readonly readonly = input<boolean>(false);
|
||||
readonly editable = input<boolean>(true);
|
||||
readonly allowEditing = input<boolean>(false);
|
||||
readonly allowRemove = input<boolean>(true);
|
||||
readonly persistQuantityChanges = input<boolean>(true);
|
||||
@@ -124,6 +125,10 @@ export class CartComponent {
|
||||
}
|
||||
|
||||
protected onItemQuantityChange(index: number, newQuantity: number): void {
|
||||
if (!this.editable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const mockItem = this.items()[index];
|
||||
if (!mockItem) {
|
||||
return;
|
||||
@@ -204,7 +209,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',
|
||||
})
|
||||
@@ -220,7 +225,7 @@ export class CartComponent {
|
||||
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
|
||||
|
||||
protected toggleEditing(): void {
|
||||
if (this.editingDisabled()) {
|
||||
if (!this.editable() || this.editingDisabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -254,7 +259,7 @@ export class CartComponent {
|
||||
|
||||
return {
|
||||
cartItemId: item.id,
|
||||
productName: item.product?.nombre ?? 'este producto',
|
||||
productName: item.nombre ?? 'este producto',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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,12 +1,13 @@
|
||||
<div class="hero-banner-container">
|
||||
<div
|
||||
class="hero-banner position-relative rounded"
|
||||
>
|
||||
<div
|
||||
class="hero-media"
|
||||
aria-hidden="true"
|
||||
[ngStyle]="{'background-image': heroConfig?.background_image_id ? 'url(' + heroConfig.background_image_id + ')' : 'none'}"
|
||||
></div>
|
||||
<div class="hero-banner position-relative rounded">
|
||||
@if (desktopImageUrl) {
|
||||
<picture class="hero-media" aria-hidden="true">
|
||||
@if (mobileImageUrl) {
|
||||
<source media="(max-width: 767.98px)" [srcset]="mobileImageUrl" />
|
||||
}
|
||||
<img [src]="desktopImageUrl" alt="" />
|
||||
</picture>
|
||||
}
|
||||
|
||||
@if (heroConfig) {
|
||||
<div
|
||||
@@ -20,7 +21,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>
|
||||
@@ -29,37 +33,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;
|
||||
}
|
||||
|
||||
@@ -13,16 +12,30 @@
|
||||
.hero-media {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
border-radius: inherit;
|
||||
|
||||
img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
&::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 +52,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 +62,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 +81,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 +92,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 +109,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 +166,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 +179,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 +238,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 +277,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,72 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { HeroBannerComponent } from './hero-banner.component';
|
||||
|
||||
describe('HeroBannerComponent', () => {
|
||||
it('renders desktop and mobile crop variants', async () => {
|
||||
await TestBed.configureTestingModule({ imports: [HeroBannerComponent] }).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(HeroBannerComponent);
|
||||
fixture.componentRef.setInput('heroConfig', {
|
||||
background_image_id: {
|
||||
desktop: 'https://example.com/desktop.jpg',
|
||||
mobile: 'https://example.com/mobile.jpg',
|
||||
},
|
||||
});
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
|
||||
expect(element.querySelector('source')?.getAttribute('srcset')).toBe(
|
||||
'https://example.com/mobile.jpg',
|
||||
);
|
||||
expect(element.querySelector('img')?.getAttribute('src')).toBe(
|
||||
'https://example.com/desktop.jpg',
|
||||
);
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,20 @@ export class HeroBannerComponent {
|
||||
@Input() heroConfig?: HeroConfig | null;
|
||||
@Input() eventConfig?: EventConfig | null;
|
||||
|
||||
protected schedulesExpanded = false;
|
||||
|
||||
protected get desktopImageUrl(): string | null {
|
||||
const image = this.heroConfig?.background_image_id;
|
||||
|
||||
return typeof image === 'string' ? image : (image?.desktop ?? null);
|
||||
}
|
||||
|
||||
protected get mobileImageUrl(): string | null {
|
||||
const image = this.heroConfig?.background_image_id;
|
||||
|
||||
return typeof image === 'string' ? image : (image?.mobile ?? image?.desktop ?? null);
|
||||
}
|
||||
|
||||
get formattedDates(): string {
|
||||
if (this.eventConfig?.dates_text) {
|
||||
return this.eventConfig.dates_text;
|
||||
@@ -27,4 +41,28 @@ export class HeroBannerComponent {
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,17 @@
|
||||
}
|
||||
}
|
||||
|
||||
.icon-btn--bordered {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border: 1px solid var(--border-color);
|
||||
|
||||
&:hover:not(:disabled),
|
||||
&:focus-visible:not(:disabled) {
|
||||
border-color: currentcolor;
|
||||
}
|
||||
}
|
||||
|
||||
// Hover/Active/Focus colors (non-disabled)
|
||||
.icon-btn:hover:not(:disabled),
|
||||
.icon-btn:focus-visible:not(:disabled),
|
||||
|
||||
@@ -22,6 +22,7 @@ export type IconButtonVariant =
|
||||
})
|
||||
export class IconButtonComponent {
|
||||
readonly variant = input.required<IconButtonVariant>();
|
||||
readonly bordered = input(false);
|
||||
readonly disabled = input(false);
|
||||
readonly ariaLabel = input<string>('');
|
||||
readonly ariaExpanded = input<boolean | null>(null);
|
||||
@@ -45,6 +46,10 @@ export class IconButtonComponent {
|
||||
});
|
||||
|
||||
protected readonly buttonClasses = computed(() => {
|
||||
return ['icon-btn', `icon-btn--${this.variant()}`];
|
||||
return {
|
||||
'icon-btn': true,
|
||||
[`icon-btn--${this.variant()}`]: true,
|
||||
'icon-btn--bordered': this.bordered(),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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,8 @@
|
||||
[title]="item.nombre"
|
||||
[description]="item.descripcion ?? ''"
|
||||
[price]="price(item)"
|
||||
[variants]="variantsFor(item)"
|
||||
[variants]="item.variants ?? []"
|
||||
[saving]="savingProductIds().has(item.id)"
|
||||
(buy)="emitRowBuy(item, $event)"
|
||||
(addToCart)="emitRowCart(item, $event)"
|
||||
/>
|
||||
@@ -23,10 +24,22 @@
|
||||
[description]="item.descripcion ?? ''"
|
||||
[price]="price(item)"
|
||||
[variants]="item.variants ?? []"
|
||||
[saving]="savingProductIds().has(item.id)"
|
||||
(buy)="emitColumnBuy(item, $event)"
|
||||
(addToCart)="emitColumnCart(item, $event)"
|
||||
/>
|
||||
}
|
||||
@case ('ticket_selector') {
|
||||
<app-product-ticket-selector
|
||||
[productId]="item.id"
|
||||
[title]="item.nombre"
|
||||
[description]="item.descripcion ?? ''"
|
||||
[price]="price(item)"
|
||||
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
||||
[disabled]="loading()"
|
||||
(buy)="emitTicketBuy(item, $event)"
|
||||
/>
|
||||
}
|
||||
@default {
|
||||
<app-product-column-with-image
|
||||
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
||||
@@ -54,8 +67,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;
|
||||
|
||||
@@ -1,18 +1,24 @@
|
||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { of } from 'rxjs';
|
||||
|
||||
import { ApiPaginatedResponse } from '../../../core/services/api-paginated-response.interface';
|
||||
import { CartService } from '../../../core/services/cart/cart.service';
|
||||
import { CatalogService } from '../../../core/services/catalog/catalog.service';
|
||||
import {
|
||||
CatalogFeaturedItems,
|
||||
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 +27,7 @@ describe('ProductListComponent', () => {
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
type: 'product',
|
||||
nombre: 'Producto dos',
|
||||
descripcion: 'Segunda descripcion',
|
||||
precio: 200,
|
||||
@@ -47,7 +54,29 @@ describe('ProductListComponent', () => {
|
||||
productItems: CatalogFeaturedItems = paginatedItems(),
|
||||
groupLayout: CatalogGroupLayout = 'paginated',
|
||||
) {
|
||||
await TestBed.configureTestingModule({ imports: [ProductListComponent] }).compileComponents();
|
||||
const getVariantOptions = vi.fn().mockReturnValue(
|
||||
of({
|
||||
selectors: ['tipo', 'sector', 'fila', 'asiento'].map((key, index) => ({
|
||||
key,
|
||||
label: key,
|
||||
options: [{ value: String(index + 1), label: String(index + 1) }],
|
||||
enabled: index === 0,
|
||||
})),
|
||||
selected_values: {},
|
||||
resolved_variant: null,
|
||||
valid: true,
|
||||
available_variant_count: 2,
|
||||
matching_variant_count: 2,
|
||||
price_range: { minimum: '10000.00', maximum: '12000.00' },
|
||||
}),
|
||||
);
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [ProductListComponent],
|
||||
providers: [
|
||||
{ provide: CatalogService, useValue: { getVariantOptions } },
|
||||
{ provide: CartService, useValue: {} },
|
||||
],
|
||||
}).compileComponents();
|
||||
const fixture = TestBed.createComponent(ProductListComponent);
|
||||
fixture.componentRef.setInput('layout', layout);
|
||||
fixture.componentRef.setInput('groupLayout', groupLayout);
|
||||
@@ -216,6 +245,101 @@ 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['patchRow'](1, {
|
||||
variantId: 401,
|
||||
reservedVariantId: 401,
|
||||
cartItemId: 1,
|
||||
status: 'reserved',
|
||||
});
|
||||
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['patchRow'](2, {
|
||||
variantId: 402,
|
||||
reservedVariantId: 402,
|
||||
cartItemId: 2,
|
||||
status: 'reserved',
|
||||
});
|
||||
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,
|
||||
reservedInCart: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('loads ticket selector availability without requiring catalog variants', async () => {
|
||||
const ticket: ProductListItem = {
|
||||
...items[0],
|
||||
variants: undefined,
|
||||
};
|
||||
const fixture = await render('ticket_selector', [ticket], 'single');
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
|
||||
const selector = fixture.debugElement.query(By.directive(ProductTicketSelectorComponent))
|
||||
.componentInstance as ProductTicketSelectorComponent;
|
||||
|
||||
expect(selector['availableVariantCount']()).toBe(2);
|
||||
expect(fixture.nativeElement.querySelectorAll('.variant-selector__select')).toHaveLength(4);
|
||||
});
|
||||
|
||||
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,7 +39,9 @@ export interface ProductListBuyEvent {
|
||||
product: ProductListItem;
|
||||
quantity: number;
|
||||
variant?: number | null;
|
||||
variantIds?: number[];
|
||||
directPurchase: boolean;
|
||||
reservedInCart?: boolean;
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -53,6 +53,7 @@ export interface ProductListBuyEvent {
|
||||
PaginatorComponent,
|
||||
ProductRowCardComponent,
|
||||
ProductVerticalWithCartCardComponent,
|
||||
ProductTicketSelectorComponent,
|
||||
],
|
||||
templateUrl: './product-list.component.html',
|
||||
styleUrl: './product-list.component.scss',
|
||||
@@ -67,6 +68,8 @@ 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 savingProductIds = input<ReadonlySet<number>>(new Set<number>());
|
||||
|
||||
readonly buy = output<ProductListBuyEvent>();
|
||||
readonly addToCart = output<ProductListCartEvent>();
|
||||
@@ -105,15 +108,6 @@ export class ProductListComponent {
|
||||
return Number.isFinite(price) ? price : 0;
|
||||
}
|
||||
|
||||
protected variantsFor(item: ProductListItem): RowVariant[] {
|
||||
return (item.variants ?? []).map((variant) => ({
|
||||
value: variant.id,
|
||||
descripcion: variant.descripcion,
|
||||
precio: variant.precio,
|
||||
values: variant.values,
|
||||
}));
|
||||
}
|
||||
|
||||
protected emitRowCart(
|
||||
product: ProductListItem,
|
||||
event: { quantity: number; variant: unknown },
|
||||
@@ -159,4 +153,15 @@ 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,
|
||||
reservedInCart: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
<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">
|
||||
@@ -13,30 +11,32 @@
|
||||
}
|
||||
</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: Attribute selects, Quantity, and Agregar al carrito button -->
|
||||
<div class="d-flex align-items-center justify-content-end gap-2">
|
||||
<app-variant-selector
|
||||
class="product-row-card__selectors"
|
||||
[variants]="variants()"
|
||||
[(selectedVariant)]="selectedVariant"
|
||||
/>
|
||||
|
||||
<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>
|
||||
<app-button variant="secondary" [disabled]="saving()" (click)="onAddToCart()">
|
||||
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}
|
||||
</app-button>
|
||||
</div>
|
||||
</div>
|
||||
</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;
|
||||
@@ -26,14 +31,42 @@
|
||||
}
|
||||
|
||||
&__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;
|
||||
}
|
||||
|
||||
&__actions {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, auto) minmax(0, 230px);
|
||||
align-items: stretch;
|
||||
gap: 0.75rem 2.5rem;
|
||||
}
|
||||
|
||||
&__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%;
|
||||
@@ -46,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ export interface Variant extends VariantSelectorVariant {
|
||||
label?: string;
|
||||
descripcion?: string | null;
|
||||
precio?: string | number;
|
||||
stock_tecnico?: number | null;
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -26,6 +27,7 @@ export class ProductRowCardComponent {
|
||||
readonly description = input<string>('');
|
||||
readonly price = input<number>(0);
|
||||
readonly variants = input<Variant[]>([]);
|
||||
readonly saving = input(false);
|
||||
|
||||
// Internal state models
|
||||
readonly quantity = model<number>(1);
|
||||
@@ -36,7 +38,7 @@ export class ProductRowCardComponent {
|
||||
readonly addToCart = output<{ quantity: number; variant: unknown }>();
|
||||
|
||||
protected readonly selectedVariantData = computed(() =>
|
||||
this.variants().find((variant) => Object.is(variant.value, this.selectedVariant())),
|
||||
this.variants().find((variant) => Object.is(variant.id, this.selectedVariant())),
|
||||
);
|
||||
protected readonly effectiveDescription = computed(
|
||||
() => this.selectedVariantData()?.descripcion ?? this.description(),
|
||||
@@ -50,6 +52,10 @@ export class ProductRowCardComponent {
|
||||
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||
|
||||
protected onAddToCart(): void {
|
||||
if (this.saving()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.addToCart.emit({
|
||||
quantity: this.quantity(),
|
||||
variant: this.selectedVariant(),
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
<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">
|
||||
<div class="ticket-selector__row-content">
|
||||
<div class="ticket-selector__fields variant-selector">
|
||||
@for (selector of row.selectors; track selector.key) {
|
||||
<select
|
||||
class="form-select variant-selector__select"
|
||||
[attr.aria-label]="selector.label"
|
||||
[disabled]="rowDisabled(row) || !selector.enabled"
|
||||
(change)="onSelectionKeyChange(row.id, selector, $any($event.target).value)"
|
||||
>
|
||||
<option
|
||||
value=""
|
||||
disabled
|
||||
[selected]="selectedOptionKey(row, selector.key) === ''"
|
||||
>
|
||||
Seleccioná {{ selector.label }}
|
||||
</option>
|
||||
@for (option of selector.options; track $index) {
|
||||
<option
|
||||
[value]="optionKey(option)"
|
||||
[selected]="optionKey(option) === selectedOptionKey(row, selector.key)"
|
||||
>
|
||||
{{ optionLabel(option) }}
|
||||
</option>
|
||||
}
|
||||
</select>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (row.status === 'reserving') {
|
||||
<span class="ticket-selector__row-status" role="status" aria-live="polite">
|
||||
Guardando...
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
<app-icon-button
|
||||
variant="trash"
|
||||
[bordered]="true"
|
||||
ariaLabel="Eliminar entrada"
|
||||
[disabled]="rowDisabled(row)"
|
||||
(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 (availableVariantCount() === 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,167 @@
|
||||
: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: inline-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: start;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
&__row-content {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
&__fields {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(120px, 1fr));
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.variant-selector__select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 38px;
|
||||
color: #666;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
&__add-row {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin-top: 0.5rem;
|
||||
|
||||
::ng-deep .ticket-selector__add-row-button {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
&__row-status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
margin-top: 0.35rem;
|
||||
color: #777;
|
||||
font-size: 13px;
|
||||
|
||||
&::before {
|
||||
width: 0.8rem;
|
||||
height: 0.8rem;
|
||||
border: 2px solid currentcolor;
|
||||
border-right-color: transparent;
|
||||
border-radius: 50%;
|
||||
animation: ticket-selector-spin 0.7s linear infinite;
|
||||
content: '';
|
||||
}
|
||||
}
|
||||
|
||||
&__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;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes ticket-selector-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ticket-selector__row-status::before {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767.98px) {
|
||||
.ticket-selector {
|
||||
&__header {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
&__fields {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
&__map {
|
||||
margin-top: 2rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
import '@angular/compiler';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { signal } from '@angular/core';
|
||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||
import { of, Subject, throwError } from 'rxjs';
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { CartService } from '../../../core/services/cart/cart.service';
|
||||
import { CatalogService } from '../../../core/services/catalog/catalog.service';
|
||||
import { ModalService } from '../../../core/services/modal.service';
|
||||
import { ToastService } from '../../../core/services/toast.service';
|
||||
import { ProductTicketSelectorComponent } from './product-ticket-selector.component';
|
||||
|
||||
const attributes = [
|
||||
{ key: 'tipo', label: 'Tipo' },
|
||||
{ key: 'sector', label: 'Sector' },
|
||||
{ key: 'fila', label: 'Fila' },
|
||||
{ key: 'asiento', label: 'Asiento' },
|
||||
];
|
||||
|
||||
function variant(id: number, tipo: string, sector: string, fila: string, asiento: string) {
|
||||
return {
|
||||
id,
|
||||
precio: '10000.00',
|
||||
stock_tecnico: 1,
|
||||
values: { tipo, sector, fila, asiento },
|
||||
};
|
||||
}
|
||||
|
||||
function mapResponse(variants: ReturnType<typeof variant>[]) {
|
||||
return {
|
||||
variants,
|
||||
selectors: attributes.map(({ key, label }, index) => ({
|
||||
key,
|
||||
label,
|
||||
options: index === 0 ? ['general'] : [],
|
||||
enabled: index === 0,
|
||||
})),
|
||||
selected_values: {},
|
||||
resolved_variant: null,
|
||||
valid: variants.length > 0,
|
||||
available_variant_count: variants.length,
|
||||
matching_variant_count: variants.length,
|
||||
price_range: { minimum: '10000.00', maximum: '10000.00' },
|
||||
};
|
||||
}
|
||||
|
||||
function cartWith(item: ReturnType<typeof variant> | null = null) {
|
||||
return {
|
||||
id: 10,
|
||||
tenant_codigo: 'demo',
|
||||
status: 'active',
|
||||
subtotal: item === null ? '0.00' : '10000.00',
|
||||
items:
|
||||
item === null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
id: 25,
|
||||
cantidad: 1,
|
||||
precio_unitario: '10000.00',
|
||||
catalog_item_id: 7,
|
||||
variant_id: item.id,
|
||||
nombre: 'Entrada',
|
||||
imagen: null,
|
||||
variant: item,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe('ProductTicketSelectorComponent', () => {
|
||||
beforeAll(() => {
|
||||
try {
|
||||
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
|
||||
} catch {
|
||||
// Test environment may already be initialized by another setup entrypoint.
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(() => TestBed.resetTestingModule());
|
||||
|
||||
async function createComponent({
|
||||
maps,
|
||||
addItem = vi.fn(),
|
||||
cartState = signal(cartWith()),
|
||||
toastDanger = vi.fn(),
|
||||
}: {
|
||||
maps: ReturnType<typeof mapResponse>[];
|
||||
addItem?: ReturnType<typeof vi.fn>;
|
||||
cartState?: ReturnType<typeof signal<ReturnType<typeof cartWith>>>;
|
||||
toastDanger?: ReturnType<typeof vi.fn>;
|
||||
}) {
|
||||
const getVariantOptions = vi.fn();
|
||||
maps.forEach((response) => getVariantOptions.mockReturnValueOnce(of(response)));
|
||||
const catalogService = { withoutLoading: vi.fn(), getVariantOptions };
|
||||
const cartService = {
|
||||
cart: cartState.asReadonly(),
|
||||
withoutLoading: vi.fn(),
|
||||
addItem,
|
||||
updateItemVariant: vi.fn(),
|
||||
removeItem: vi.fn().mockReturnValue(of({ data: cartWith() })),
|
||||
};
|
||||
catalogService.withoutLoading.mockReturnValue(catalogService);
|
||||
cartService.withoutLoading.mockReturnValue(cartService);
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [ProductTicketSelectorComponent],
|
||||
providers: [
|
||||
{ provide: CatalogService, useValue: catalogService },
|
||||
{ provide: CartService, useValue: cartService },
|
||||
{
|
||||
provide: ModalService,
|
||||
useValue: { openConfirmDelete: vi.fn().mockReturnValue(of(true)) },
|
||||
},
|
||||
{ provide: ToastService, useValue: { danger: toastDanger } },
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(ProductTicketSelectorComponent);
|
||||
fixture.componentRef.setInput('productId', 7);
|
||||
fixture.componentRef.setInput('title', 'Entrada');
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
|
||||
return { fixture, getVariantOptions, cartService, toastDanger };
|
||||
}
|
||||
|
||||
it('loads one map, recalculates the cascade locally and reserves only after the last select', async () => {
|
||||
const selectedVariant = variant(401, 'general', 'A', '1', '1');
|
||||
const variants = [
|
||||
selectedVariant,
|
||||
variant(402, 'general', 'A', '1', '2'),
|
||||
variant(403, 'general', 'B', '2', '1'),
|
||||
];
|
||||
const addItem = vi.fn().mockReturnValue(of({ data: cartWith(selectedVariant) }));
|
||||
const { fixture, getVariantOptions } = await createComponent({
|
||||
maps: [mapResponse(variants)],
|
||||
addItem,
|
||||
});
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
expect(getVariantOptions).toHaveBeenCalledTimes(1);
|
||||
expect(getVariantOptions).toHaveBeenCalledWith(7, { selected_values: {} });
|
||||
|
||||
component['onSelectionChange'](1, 'tipo', 'general');
|
||||
component['onSelectionChange'](1, 'sector', 'A');
|
||||
component['onSelectionChange'](1, 'fila', '1');
|
||||
|
||||
expect(getVariantOptions).toHaveBeenCalledTimes(1);
|
||||
expect(addItem).not.toHaveBeenCalled();
|
||||
expect(component['rows']()[0].selectors[3]).toMatchObject({
|
||||
key: 'asiento',
|
||||
options: ['1', '2'],
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
component['onSelectionChange'](1, 'asiento', '1');
|
||||
|
||||
expect(getVariantOptions).toHaveBeenCalledTimes(1);
|
||||
expect(addItem).toHaveBeenCalledWith(7, 401, 1);
|
||||
expect(component['rows']()[0]).toMatchObject({
|
||||
variantId: 401,
|
||||
reservedVariantId: 401,
|
||||
status: 'reserved',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows a saving status while the selected seat is being reserved', async () => {
|
||||
const selectedVariant = variant(401, 'general', 'A', '1', '1');
|
||||
const reservation = new Subject<{ data: ReturnType<typeof cartWith> }>();
|
||||
const addItem = vi.fn().mockReturnValue(reservation);
|
||||
const { fixture } = await createComponent({
|
||||
maps: [mapResponse([selectedVariant])],
|
||||
addItem,
|
||||
});
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
component['onSelectionChange'](1, 'tipo', 'general');
|
||||
component['onSelectionChange'](1, 'sector', 'A');
|
||||
component['onSelectionChange'](1, 'fila', '1');
|
||||
component['onSelectionChange'](1, 'asiento', '1');
|
||||
fixture.detectChanges();
|
||||
|
||||
const savingStatus = fixture.nativeElement.querySelector(
|
||||
'.ticket-selector__row-status',
|
||||
) as HTMLElement | null;
|
||||
expect(savingStatus?.textContent?.trim()).toBe('Guardando...');
|
||||
expect(savingStatus?.getAttribute('role')).toBe('status');
|
||||
|
||||
reservation.next({ data: cartWith(selectedVariant) });
|
||||
reservation.complete();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.nativeElement.querySelector('.ticket-selector__row-status')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows the remove action as a bordered icon button', async () => {
|
||||
const { fixture } = await createComponent({
|
||||
maps: [mapResponse([variant(401, 'general', 'A', '1', '1')])],
|
||||
});
|
||||
|
||||
const removeButton = fixture.nativeElement.querySelector(
|
||||
'app-icon-button[ariaLabel="Eliminar entrada"] button',
|
||||
) as HTMLButtonElement | null;
|
||||
|
||||
expect(removeButton?.classList.contains('icon-btn--bordered')).toBe(true);
|
||||
});
|
||||
|
||||
it('clears only the seat after a stock conflict when the row still has alternatives', async () => {
|
||||
const failed = variant(401, 'general', 'A', '1', '1');
|
||||
const alternative = variant(402, 'general', 'A', '1', '2');
|
||||
const message = 'El asiento ya no está disponible.';
|
||||
const addItem = vi.fn().mockReturnValue(
|
||||
throwError(
|
||||
() =>
|
||||
new HttpErrorResponse({
|
||||
status: 422,
|
||||
error: { message },
|
||||
}),
|
||||
),
|
||||
);
|
||||
const { fixture, getVariantOptions, toastDanger } = await createComponent({
|
||||
maps: [mapResponse([failed, alternative]), mapResponse([alternative])],
|
||||
addItem,
|
||||
});
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
component['onSelectionChange'](1, 'tipo', 'general');
|
||||
component['onSelectionChange'](1, 'sector', 'A');
|
||||
component['onSelectionChange'](1, 'fila', '1');
|
||||
component['onSelectionChange'](1, 'asiento', '1');
|
||||
|
||||
expect(getVariantOptions).toHaveBeenCalledTimes(2);
|
||||
expect(component['rows']()[0]).toMatchObject({
|
||||
selectedValues: { tipo: 'general', sector: 'A', fila: '1' },
|
||||
variantId: null,
|
||||
status: 'selecting',
|
||||
error: message,
|
||||
});
|
||||
expect(component['rows']()[0].selectors[3].options).toEqual(['2']);
|
||||
expect(toastDanger).toHaveBeenCalledWith(message);
|
||||
});
|
||||
|
||||
it('also clears the row when the refreshed map has no seats for that row', async () => {
|
||||
const failed = variant(401, 'general', 'A', '1', '1');
|
||||
const otherRow = variant(402, 'general', 'A', '2', '1');
|
||||
const addItem = vi
|
||||
.fn()
|
||||
.mockReturnValue(
|
||||
throwError(() => new HttpErrorResponse({ status: 422, error: { message: 'Sin stock.' } })),
|
||||
);
|
||||
const { fixture } = await createComponent({
|
||||
maps: [mapResponse([failed, otherRow]), mapResponse([otherRow])],
|
||||
addItem,
|
||||
});
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
component['onSelectionChange'](1, 'tipo', 'general');
|
||||
component['onSelectionChange'](1, 'sector', 'A');
|
||||
component['onSelectionChange'](1, 'fila', '1');
|
||||
component['onSelectionChange'](1, 'asiento', '1');
|
||||
|
||||
expect(component['rows']()[0].selectedValues).toEqual({ tipo: 'general', sector: 'A' });
|
||||
expect(component['rows']()[0].selectors[2]).toMatchObject({
|
||||
key: 'fila',
|
||||
options: ['2'],
|
||||
enabled: true,
|
||||
});
|
||||
expect(component['rows']()[0].selectors[3].enabled).toBe(false);
|
||||
});
|
||||
|
||||
it('restores a variant already reserved in the cart without another options request', async () => {
|
||||
const reserved = variant(401, 'general', 'A', '1', '1');
|
||||
const cartState = signal(cartWith(reserved));
|
||||
const { fixture, getVariantOptions, cartService } = await createComponent({
|
||||
maps: [mapResponse([])],
|
||||
cartState,
|
||||
});
|
||||
|
||||
expect(getVariantOptions).toHaveBeenCalledTimes(1);
|
||||
expect(cartService.updateItemVariant).not.toHaveBeenCalled();
|
||||
expect(fixture.componentInstance['rows']()[0]).toMatchObject({
|
||||
variantId: 401,
|
||||
reservedVariantId: 401,
|
||||
cartItemId: 25,
|
||||
selectedValues: { tipo: 'general', sector: 'A', fila: '1', asiento: '1' },
|
||||
status: 'reserved',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,625 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import {
|
||||
afterNextRender,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
DestroyRef,
|
||||
effect,
|
||||
inject,
|
||||
input,
|
||||
output,
|
||||
signal,
|
||||
untracked,
|
||||
} from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { Subscription } from 'rxjs';
|
||||
|
||||
import { CartItem } from '../../../core/services/cart/cart.interface';
|
||||
import { CartService } from '../../../core/services/cart/cart.service';
|
||||
import {
|
||||
CatalogFeaturedItemVariant,
|
||||
CatalogVariantOptionsResponse,
|
||||
CatalogVariantSelector,
|
||||
CatalogVariantValue,
|
||||
} from '../../../core/services/catalog/catalog.interface';
|
||||
import { CatalogService } from '../../../core/services/catalog/catalog.service';
|
||||
import { ModalService } from '../../../core/services/modal.service';
|
||||
import { ToastService } from '../../../core/services/toast.service';
|
||||
import { ButtonComponent } from '../button/button.component';
|
||||
import { IconButtonComponent } from '../icon-button/icon-button.component';
|
||||
|
||||
type TicketSelectionStatus =
|
||||
| 'selecting'
|
||||
| 'checking'
|
||||
| 'reserving'
|
||||
| 'reserved'
|
||||
| 'removing'
|
||||
| 'error';
|
||||
|
||||
interface VariantAttribute {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface TicketSelectionRow {
|
||||
id: number;
|
||||
variantId: number | null;
|
||||
reservedVariantId: number | null;
|
||||
cartItemId: number | null;
|
||||
selectedValues: Record<string, string | string[]>;
|
||||
selectors: CatalogVariantSelector[];
|
||||
reservedSelectedValues: Record<string, string | string[]>;
|
||||
status: TicketSelectionStatus;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-product-ticket-selector',
|
||||
imports: [ButtonComponent, IconButtonComponent],
|
||||
templateUrl: './product-ticket-selector.component.html',
|
||||
styleUrl: './product-ticket-selector.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class ProductTicketSelectorComponent {
|
||||
private readonly catalogService = inject(CatalogService);
|
||||
private readonly cartService = inject(CartService);
|
||||
private readonly modalService = inject(ModalService);
|
||||
private readonly toastService = inject(ToastService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly reservationRequests = new Map<number, Subscription>();
|
||||
private readonly viewReady = signal(false);
|
||||
private readonly mapReady = signal(false);
|
||||
private readonly variants = signal<CatalogFeaturedItemVariant[]>([]);
|
||||
private readonly attributes = signal<VariantAttribute[]>([]);
|
||||
private mapRequest: Subscription | null = null;
|
||||
|
||||
readonly productId = input.required<number>();
|
||||
readonly title = input.required<string>();
|
||||
readonly description = input<string>('');
|
||||
readonly price = input<number>(0);
|
||||
readonly imageUrl = input<string | null>(null);
|
||||
readonly disabled = input(false);
|
||||
|
||||
readonly buy = output<number[]>();
|
||||
|
||||
protected readonly rows = signal<TicketSelectionRow[]>([this.createRow(1)]);
|
||||
private readonly remotePriceRange = signal<{ minimum: number; maximum: number } | null>(null);
|
||||
private nextRowId = 2;
|
||||
|
||||
protected readonly availableVariantCount = computed(() => {
|
||||
const reservedIds = new Set(
|
||||
this.rows().flatMap(({ reservedVariantId }) =>
|
||||
reservedVariantId === null ? [] : [reservedVariantId],
|
||||
),
|
||||
);
|
||||
return this.variants().filter(({ id }) => !reservedIds.has(id)).length;
|
||||
});
|
||||
protected readonly hasSelection = computed(
|
||||
() =>
|
||||
this.rows().length > 0 &&
|
||||
this.rows().every(
|
||||
(row) =>
|
||||
row.status === 'reserved' &&
|
||||
row.variantId !== null &&
|
||||
row.variantId === row.reservedVariantId,
|
||||
),
|
||||
);
|
||||
protected readonly canAddRow = computed(
|
||||
() =>
|
||||
this.availableVariantCount() > 0 &&
|
||||
this.rows().every((row) => row.status === 'reserved') &&
|
||||
!this.rows().some((row) => this.isBusy(row)),
|
||||
);
|
||||
protected readonly priceRange = computed(() => {
|
||||
const range = this.remotePriceRange();
|
||||
const minimum = range?.minimum ?? this.price();
|
||||
const maximum = range?.maximum ?? this.price();
|
||||
return {
|
||||
minimum: this.formatCurrency(minimum),
|
||||
maximum: this.formatCurrency(maximum),
|
||||
hasRange: minimum !== maximum,
|
||||
};
|
||||
});
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const viewReady = this.viewReady();
|
||||
const mapReady = this.mapReady();
|
||||
const cart = this.cartService.cart?.() ?? null;
|
||||
if (!viewReady) return;
|
||||
|
||||
untracked(() => {
|
||||
if (!mapReady) {
|
||||
this.loadVariantMap();
|
||||
return;
|
||||
}
|
||||
this.synchronizeWithCart(cart?.items ?? []);
|
||||
});
|
||||
});
|
||||
|
||||
afterNextRender(() => this.viewReady.set(true));
|
||||
this.destroyRef.onDestroy(() => {
|
||||
this.mapRequest?.unsubscribe();
|
||||
this.reservationRequests.forEach((request) => request.unsubscribe());
|
||||
});
|
||||
}
|
||||
|
||||
protected onBuy(): void {
|
||||
const variantIds = this.rows().flatMap((row) =>
|
||||
row.reservedVariantId === null ? [] : [row.reservedVariantId],
|
||||
);
|
||||
if (this.hasSelection() && variantIds.length > 0) this.buy.emit(variantIds);
|
||||
}
|
||||
|
||||
protected addRow(): void {
|
||||
if (!this.canAddRow()) return;
|
||||
const row = this.createRow(this.nextRowId++);
|
||||
row.status = 'selecting';
|
||||
row.selectors = this.buildSelectors(row.selectedValues, row);
|
||||
this.rows.update((rows) => [...rows, row]);
|
||||
}
|
||||
|
||||
protected removeRow(rowId: number): void {
|
||||
const row = this.findRow(rowId);
|
||||
if (!row || this.isBusy(row)) return;
|
||||
this.modalService
|
||||
.openConfirmDelete({
|
||||
title: 'Eliminar entrada',
|
||||
content: `Se eliminará esta entrada de “${this.title()}”. Si ya estaba reservada, se liberará del carrito.`,
|
||||
confirmLabel: 'Sí, eliminar',
|
||||
cancelLabel: 'Cancelar',
|
||||
size: 'md',
|
||||
})
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe((confirmed) => {
|
||||
if (confirmed) this.confirmRemoveRow(row);
|
||||
});
|
||||
}
|
||||
|
||||
private confirmRemoveRow(row: TicketSelectionRow): void {
|
||||
if (row.cartItemId === null) {
|
||||
this.deleteRow(row.id);
|
||||
return;
|
||||
}
|
||||
this.patchRow(row.id, { status: 'removing', error: null });
|
||||
const request = this.cartService
|
||||
.withoutLoading()
|
||||
.removeItem(row.cartItemId)
|
||||
.subscribe({
|
||||
next: () => this.deleteRow(row.id),
|
||||
error: (error: HttpErrorResponse) => {
|
||||
this.patchRow(row.id, {
|
||||
status: 'reserved',
|
||||
error: this.errorMessage(error, 'No se pudo liberar la entrada.'),
|
||||
});
|
||||
},
|
||||
});
|
||||
this.reservationRequests.set(row.id, request);
|
||||
}
|
||||
|
||||
protected onSelectionChange(
|
||||
rowId: number,
|
||||
selectorKey: string,
|
||||
value: CatalogVariantValue | null,
|
||||
): void {
|
||||
const row = this.findRow(rowId);
|
||||
if (!row || this.isBusy(row)) return;
|
||||
const selectorIndex = this.attributes().findIndex(({ key }) => key === selectorKey);
|
||||
if (selectorIndex < 0) return;
|
||||
|
||||
const selectedValues = { ...row.selectedValues };
|
||||
if (value === null) delete selectedValues[selectorKey];
|
||||
else selectedValues[selectorKey] = this.normalizeValue(value);
|
||||
this.attributes()
|
||||
.slice(selectorIndex + 1)
|
||||
.forEach(({ key }) => delete selectedValues[key]);
|
||||
|
||||
const variant = this.resolveVariant(row, selectedValues);
|
||||
this.patchRow(rowId, {
|
||||
variantId: variant?.id ?? null,
|
||||
selectedValues,
|
||||
selectors: this.buildSelectors(selectedValues, row),
|
||||
status: 'selecting',
|
||||
error: null,
|
||||
});
|
||||
if (variant !== null) this.reserveRow(rowId, variant.id, selectedValues);
|
||||
}
|
||||
|
||||
protected optionLabel(value: CatalogVariantValue): string {
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
return values.map((item) => (typeof item === 'string' ? item : item.label)).join(', ');
|
||||
}
|
||||
|
||||
protected selectedOption(row: TicketSelectionRow, key: string): string | string[] | null {
|
||||
return row.selectedValues[key] ?? null;
|
||||
}
|
||||
|
||||
protected optionKey(value: CatalogVariantValue): string {
|
||||
return this.valueKey(value);
|
||||
}
|
||||
|
||||
protected selectedOptionKey(row: TicketSelectionRow, key: string): string {
|
||||
const selectedOption = this.selectedOption(row, key);
|
||||
return selectedOption === null ? '' : this.valueKey(selectedOption);
|
||||
}
|
||||
|
||||
protected onSelectionKeyChange(
|
||||
rowId: number,
|
||||
selector: CatalogVariantSelector,
|
||||
selectedKey: string,
|
||||
): void {
|
||||
const selectedOption =
|
||||
selector.options.find((option) => this.valueKey(option) === selectedKey) ?? null;
|
||||
this.onSelectionChange(rowId, selector.key, selectedOption);
|
||||
}
|
||||
|
||||
protected rowDisabled(row: TicketSelectionRow): boolean {
|
||||
return this.disabled() || this.isBusy(row);
|
||||
}
|
||||
|
||||
private loadVariantMap(
|
||||
onLoaded?: () => void,
|
||||
onError?: (error: HttpErrorResponse) => void,
|
||||
): void {
|
||||
if (this.mapRequest !== null && !onLoaded) return;
|
||||
this.mapRequest?.unsubscribe();
|
||||
const request = this.catalogService
|
||||
.withoutLoading()
|
||||
.getVariantOptions(this.productId(), { selected_values: {} })
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
this.applyVariantMap(response);
|
||||
this.mapReady.set(true);
|
||||
this.mapRequest = null;
|
||||
onLoaded?.();
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
this.mapRequest = null;
|
||||
if (onError) {
|
||||
onError(error);
|
||||
return;
|
||||
}
|
||||
const message = this.errorMessage(error, 'No se pudo consultar la disponibilidad.');
|
||||
this.rows.update((rows) =>
|
||||
rows.map((row) => ({ ...row, status: 'error', error: message })),
|
||||
);
|
||||
this.toastService.danger(message);
|
||||
},
|
||||
});
|
||||
this.mapRequest = request;
|
||||
}
|
||||
|
||||
private applyVariantMap(response: CatalogVariantOptionsResponse): void {
|
||||
this.variants.set(response.variants);
|
||||
this.attributes.set(response.selectors.map(({ key, label }) => ({ key, label })));
|
||||
this.remotePriceRange.set({
|
||||
minimum: Number(response.price_range.minimum),
|
||||
maximum: Number(response.price_range.maximum),
|
||||
});
|
||||
}
|
||||
|
||||
private buildSelectors(
|
||||
selectedValues: Record<string, string | string[]>,
|
||||
row: TicketSelectionRow,
|
||||
variants = this.availableVariantsFor(row),
|
||||
): CatalogVariantSelector[] {
|
||||
return this.attributes().map(({ key, label }, index, attributes) => {
|
||||
const previousKeys = attributes.slice(0, index).map((attribute) => attribute.key);
|
||||
const compatibleVariants = variants.filter((variant) =>
|
||||
previousKeys.every(
|
||||
(previousKey) =>
|
||||
previousKey in selectedValues &&
|
||||
this.valueKey(variant.values[previousKey]) ===
|
||||
this.valueKey(selectedValues[previousKey]),
|
||||
),
|
||||
);
|
||||
return {
|
||||
key,
|
||||
label,
|
||||
options: this.uniqueValues(compatibleVariants.map((variant) => variant.values[key])),
|
||||
enabled: index === 0 || previousKeys.every((previousKey) => previousKey in selectedValues),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private resolveVariant(
|
||||
row: TicketSelectionRow,
|
||||
selectedValues: Record<string, string | string[]>,
|
||||
): CatalogFeaturedItemVariant | null {
|
||||
const attributes = this.attributes();
|
||||
if (attributes.length === 0 || attributes.some(({ key }) => !(key in selectedValues)))
|
||||
return null;
|
||||
const matches = this.availableVariantsFor(row).filter((variant) =>
|
||||
attributes.every(
|
||||
({ key }) => this.valueKey(variant.values[key]) === this.valueKey(selectedValues[key]),
|
||||
),
|
||||
);
|
||||
return matches.length === 1 ? matches[0] : null;
|
||||
}
|
||||
|
||||
private availableVariantsFor(row: TicketSelectionRow): CatalogFeaturedItemVariant[] {
|
||||
const reservedByOtherRows = new Set(
|
||||
this.rows().flatMap((candidate) =>
|
||||
candidate.id !== row.id && candidate.reservedVariantId !== null
|
||||
? [candidate.reservedVariantId]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
const variants = [...this.variants()];
|
||||
const reservedVariant = this.reservedVariantData(row);
|
||||
if (reservedVariant !== null && !variants.some(({ id }) => id === reservedVariant.id)) {
|
||||
variants.push(reservedVariant);
|
||||
}
|
||||
return variants.filter(({ id }) => !reservedByOtherRows.has(id));
|
||||
}
|
||||
|
||||
private reservedVariantData(row: TicketSelectionRow): CatalogFeaturedItemVariant | null {
|
||||
if (row.cartItemId === null || row.reservedVariantId === null) return null;
|
||||
const item = this.cartService.cart?.()?.items.find(({ id }) => id === row.cartItemId);
|
||||
if (!item?.variant) return null;
|
||||
return {
|
||||
id: item.variant.id,
|
||||
precio: item.variant.precio,
|
||||
stock_tecnico: item.variant.stock_tecnico,
|
||||
values: item.variant.values,
|
||||
};
|
||||
}
|
||||
|
||||
private uniqueValues(values: Array<CatalogVariantValue | undefined>): CatalogVariantValue[] {
|
||||
const unique = new Map<string, CatalogVariantValue>();
|
||||
values.forEach((value) => {
|
||||
if (value !== undefined) unique.set(this.valueKey(value), value);
|
||||
});
|
||||
return [...unique.values()];
|
||||
}
|
||||
|
||||
private reserveRow(
|
||||
rowId: number,
|
||||
variantId: number,
|
||||
selectedValues: Record<string, string | string[]>,
|
||||
): void {
|
||||
const row = this.findRow(rowId);
|
||||
if (!row || (row.status === 'reserved' && row.reservedVariantId === variantId)) return;
|
||||
this.patchRow(rowId, { status: 'reserving', error: null });
|
||||
const cartService = this.cartService.withoutLoading();
|
||||
const operation =
|
||||
row.cartItemId === null
|
||||
? cartService.addItem(this.productId(), variantId, 1)
|
||||
: cartService.updateItemVariant(row.cartItemId, 1, variantId);
|
||||
const request = operation.subscribe({
|
||||
next: (response) => {
|
||||
const cartItem =
|
||||
row.cartItemId === null
|
||||
? response.data.items.find(
|
||||
(item) =>
|
||||
item.catalog_item_id === this.productId() && item.variant_id === variantId,
|
||||
)
|
||||
: response.data.items.find((item) => item.id === row.cartItemId);
|
||||
if (!cartItem) {
|
||||
this.patchRow(rowId, {
|
||||
variantId: row.reservedVariantId,
|
||||
status: row.reservedVariantId === null ? 'error' : 'reserved',
|
||||
error: 'No se pudo identificar la entrada reservada.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
const currentRow = this.findRow(rowId) ?? row;
|
||||
this.patchRow(rowId, {
|
||||
variantId,
|
||||
reservedVariantId: variantId,
|
||||
selectedValues,
|
||||
selectors: this.buildSelectors(selectedValues, currentRow),
|
||||
reservedSelectedValues: selectedValues,
|
||||
cartItemId: cartItem.id,
|
||||
status: 'reserved',
|
||||
error: null,
|
||||
});
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
const message = this.errorMessage(error, 'La entrada ya no está disponible.');
|
||||
if (error.status === 422) {
|
||||
this.recoverFromUnavailableVariant(rowId, variantId, message);
|
||||
return;
|
||||
}
|
||||
this.restoreReservedRowAfterError(rowId, row, message);
|
||||
},
|
||||
});
|
||||
this.reservationRequests.set(rowId, request);
|
||||
}
|
||||
|
||||
private recoverFromUnavailableVariant(
|
||||
rowId: number,
|
||||
failedVariantId: number,
|
||||
message: string,
|
||||
): void {
|
||||
this.patchRow(rowId, { status: 'checking', error: null });
|
||||
this.loadVariantMap(
|
||||
() => this.backtrackSelection(rowId, failedVariantId, message),
|
||||
() => {
|
||||
const row = this.findRow(rowId);
|
||||
if (row) this.restoreReservedRowAfterError(rowId, row, message);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private backtrackSelection(rowId: number, failedVariantId: number, message: string): void {
|
||||
const row = this.findRow(rowId);
|
||||
if (!row) return;
|
||||
const variants = this.availableVariantsFor(row).filter(({ id }) => id !== failedVariantId);
|
||||
const selectedValues = { ...row.selectedValues };
|
||||
const attributes = this.attributes();
|
||||
|
||||
for (let index = attributes.length - 1; index >= 0; index--) {
|
||||
delete selectedValues[attributes[index].key];
|
||||
const prefixKeys = attributes.slice(0, index).map(({ key }) => key);
|
||||
const hasCompatibleVariant = variants.some((variant) =>
|
||||
prefixKeys.every(
|
||||
(key) =>
|
||||
key in selectedValues &&
|
||||
this.valueKey(variant.values[key]) === this.valueKey(selectedValues[key]),
|
||||
),
|
||||
);
|
||||
if (!hasCompatibleVariant) continue;
|
||||
this.patchRow(rowId, {
|
||||
variantId: null,
|
||||
selectedValues: { ...selectedValues },
|
||||
selectors: this.buildSelectors(selectedValues, row, variants),
|
||||
status: 'selecting',
|
||||
error: message,
|
||||
});
|
||||
this.toastService.danger(message);
|
||||
return;
|
||||
}
|
||||
|
||||
this.patchRow(rowId, {
|
||||
variantId: null,
|
||||
selectedValues: {},
|
||||
selectors: this.buildSelectors({}, row, variants),
|
||||
status: 'error',
|
||||
error: message,
|
||||
});
|
||||
this.toastService.danger(message);
|
||||
}
|
||||
|
||||
private restoreReservedRowAfterError(
|
||||
rowId: number,
|
||||
row: TicketSelectionRow,
|
||||
message: string,
|
||||
): void {
|
||||
if (row.reservedVariantId === null) {
|
||||
this.patchRow(rowId, { variantId: null, status: 'error', error: message });
|
||||
} else {
|
||||
const selectedValues = row.reservedSelectedValues;
|
||||
this.patchRow(rowId, {
|
||||
variantId: row.reservedVariantId,
|
||||
selectedValues,
|
||||
selectors: this.buildSelectors(selectedValues, row),
|
||||
status: 'reserved',
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
this.toastService.danger(message);
|
||||
}
|
||||
|
||||
private createRow(id: number): TicketSelectionRow {
|
||||
return {
|
||||
id,
|
||||
variantId: null,
|
||||
reservedVariantId: null,
|
||||
cartItemId: null,
|
||||
selectedValues: {},
|
||||
selectors: [],
|
||||
reservedSelectedValues: {},
|
||||
status: 'checking',
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
|
||||
private createCartRow(item: CartItem, id = this.nextRowId++): TicketSelectionRow | null {
|
||||
if (item.variant_id === null || item.variant === null) return null;
|
||||
const selectedValues = Object.fromEntries(
|
||||
Object.entries(item.variant.values).map(([key, value]) => [key, this.normalizeValue(value)]),
|
||||
);
|
||||
return {
|
||||
id,
|
||||
variantId: item.variant_id,
|
||||
reservedVariantId: item.variant_id,
|
||||
cartItemId: item.id,
|
||||
selectedValues,
|
||||
selectors: [],
|
||||
reservedSelectedValues: selectedValues,
|
||||
status: 'reserved',
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
|
||||
private synchronizeWithCart(items: CartItem[]): void {
|
||||
const cartItems = items.filter(
|
||||
(item) => item.catalog_item_id === this.productId() && item.variant_id !== null,
|
||||
);
|
||||
const currentRows = this.rows();
|
||||
if (cartItems.length === 0) {
|
||||
const localRows = currentRows.filter((row) => row.cartItemId === null);
|
||||
const rows = localRows.length > 0 ? localRows : [this.createRow(this.nextRowId++)];
|
||||
this.replaceRows(this.withRefreshedSelectors(rows));
|
||||
return;
|
||||
}
|
||||
|
||||
const synchronizedRows = cartItems.flatMap((item) => {
|
||||
const existingRow = currentRows.find((row) => row.cartItemId === item.id);
|
||||
if (existingRow?.reservedVariantId === item.variant_id) return [existingRow];
|
||||
const cartRow = this.createCartRow(item, existingRow?.id);
|
||||
return cartRow === null ? [] : [cartRow];
|
||||
});
|
||||
const localRows = currentRows.filter(
|
||||
(row) => row.cartItemId === null && Object.keys(row.selectedValues).length > 0,
|
||||
);
|
||||
this.replaceRows(this.withRefreshedSelectors([...synchronizedRows, ...localRows]));
|
||||
}
|
||||
|
||||
private withRefreshedSelectors(rows: TicketSelectionRow[]): TicketSelectionRow[] {
|
||||
const previousRows = this.rows();
|
||||
this.rows.set(rows);
|
||||
const refreshed = rows.map((row) => ({
|
||||
...row,
|
||||
status: row.status === 'checking' ? ('selecting' as const) : row.status,
|
||||
selectors: this.buildSelectors(row.selectedValues, row),
|
||||
}));
|
||||
this.rows.set(previousRows);
|
||||
return refreshed;
|
||||
}
|
||||
|
||||
private replaceRows(rows: TicketSelectionRow[]): void {
|
||||
const retainedIds = new Set(rows.map(({ id }) => id));
|
||||
this.rows().forEach((row) => {
|
||||
if (retainedIds.has(row.id)) return;
|
||||
this.reservationRequests.get(row.id)?.unsubscribe();
|
||||
this.reservationRequests.delete(row.id);
|
||||
});
|
||||
this.rows.set(rows);
|
||||
}
|
||||
|
||||
private findRow(rowId: number): TicketSelectionRow | undefined {
|
||||
return this.rows().find((row) => row.id === rowId);
|
||||
}
|
||||
|
||||
private patchRow(rowId: number, patch: Partial<TicketSelectionRow>): void {
|
||||
this.rows.update((rows) => rows.map((row) => (row.id === rowId ? { ...row, ...patch } : row)));
|
||||
}
|
||||
|
||||
private deleteRow(rowId: number): void {
|
||||
this.rows.update((rows) => rows.filter((row) => row.id !== rowId));
|
||||
this.reservationRequests.delete(rowId);
|
||||
}
|
||||
|
||||
private isBusy(row: TicketSelectionRow): boolean {
|
||||
return ['checking', 'reserving', 'removing'].includes(row.status);
|
||||
}
|
||||
|
||||
private normalizeValue(value: CatalogVariantValue): string | string[] {
|
||||
return Array.isArray(value)
|
||||
? value.map((item) => this.scalarValue(item))
|
||||
: this.scalarValue(value);
|
||||
}
|
||||
|
||||
private scalarValue(value: string | { value: string }): string {
|
||||
return typeof value === 'string' ? value : value.value;
|
||||
}
|
||||
|
||||
private valueKey(value: CatalogVariantValue): string {
|
||||
return JSON.stringify(this.normalizeValue(value));
|
||||
}
|
||||
|
||||
private errorMessage(error: HttpErrorResponse, fallback: string): string {
|
||||
return typeof error.error?.message === 'string' ? error.error.message : fallback;
|
||||
}
|
||||
|
||||
private formatCurrency(value: number): string {
|
||||
return new Intl.NumberFormat('es-AR', {
|
||||
style: 'currency',
|
||||
currency: 'ARS',
|
||||
maximumFractionDigits: 0,
|
||||
}).format(value);
|
||||
}
|
||||
}
|
||||
@@ -21,18 +21,7 @@
|
||||
</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.key) {
|
||||
<option [ngValue]="option.value">{{ option.label }}</option>
|
||||
}
|
||||
</select>
|
||||
}
|
||||
<app-variant-selector [variants]="variants()" [(selectedVariant)]="selectedVariant" />
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -47,10 +36,10 @@
|
||||
</app-button>
|
||||
<app-button
|
||||
variant="secondary"
|
||||
[disabled]="hasVariants() && selectedVariant() === null"
|
||||
[disabled]="saving() || (hasVariants() && selectedVariant() === null)"
|
||||
(click)="onAddToCart()"
|
||||
>
|
||||
Agregar al carrito
|
||||
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}
|
||||
</app-button>
|
||||
</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);
|
||||
|
||||
@@ -66,24 +66,11 @@
|
||||
}
|
||||
|
||||
&__variant-selectors {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__variant-select {
|
||||
flex: 1 1 0;
|
||||
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));
|
||||
}
|
||||
&__variant-selectors app-variant-selector {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
&__price {
|
||||
@@ -116,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');
|
||||
@@ -130,34 +130,14 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
||||
|
||||
expect(summary?.querySelector('.product-vertical-with-cart-card__price')).not.toBeNull();
|
||||
expect(summary?.querySelector('app-quantity-selector')).not.toBeNull();
|
||||
expect(
|
||||
selectors?.querySelectorAll('.product-vertical-with-cart-card__variant-select'),
|
||||
).toHaveLength(1);
|
||||
expect(selectors?.querySelectorAll('.variant-selector__select')).toHaveLength(1);
|
||||
expect(selectors?.querySelector('app-quantity-selector')).toBeNull();
|
||||
});
|
||||
|
||||
it('uses the variant value for selection and renders its label', async () => {
|
||||
const fixture = await createComponent();
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{
|
||||
id: 10,
|
||||
values: { event_date: { value: '2', label: '10/10/2026' } },
|
||||
},
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
const option = fixture.nativeElement.querySelector(
|
||||
'.product-vertical-with-cart-card__variant-select option',
|
||||
) as HTMLOptionElement;
|
||||
|
||||
expect(option.textContent?.trim()).toBe('10/10/2026');
|
||||
expect((fixture.componentInstance as any).selectedValues()).toEqual({ event_date: '2' });
|
||||
});
|
||||
|
||||
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();
|
||||
@@ -168,7 +148,7 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
||||
expect(layout?.querySelector('.product-vertical-with-cart-card__summary')).not.toBeNull();
|
||||
expect(
|
||||
layout?.querySelectorAll(
|
||||
'.product-vertical-with-cart-card__variant-selectors .product-vertical-with-cart-card__variant-select',
|
||||
'.product-vertical-with-cart-card__variant-selectors .variant-selector__select',
|
||||
),
|
||||
).toHaveLength(2);
|
||||
});
|
||||
@@ -184,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'));
|
||||
@@ -199,7 +179,7 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
||||
});
|
||||
|
||||
it('prioritizes the selected variant description and price', async () => {
|
||||
const fixture = await createComponent('Descripción general');
|
||||
const fixture = await createComponent('Descripción general');
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{
|
||||
id: 40,
|
||||
@@ -224,9 +204,7 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
||||
element.querySelector('.product-vertical-with-cart-card__price')?.textContent?.trim(),
|
||||
).toBe('$ 10.000');
|
||||
|
||||
const select = element.querySelector(
|
||||
'.product-vertical-with-cart-card__variant-select',
|
||||
) as HTMLSelectElement;
|
||||
const select = element.querySelector('.variant-selector__select') as HTMLSelectElement;
|
||||
select.value = select.options[1].value;
|
||||
select.dispatchEvent(new Event('change'));
|
||||
fixture.detectChanges();
|
||||
|
||||
@@ -1,44 +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 { VariantAttributeValue } from '../../../core/services/catalog/catalog.interface';
|
||||
import {
|
||||
VariantSelectorComponent,
|
||||
VariantSelectorVariant,
|
||||
} from '../variant-selector/variant-selector.component';
|
||||
|
||||
type VariantSelectionValue = string | string[];
|
||||
|
||||
export interface VerticalCartVariant {
|
||||
id: number;
|
||||
export interface VerticalCartVariant extends VariantSelectorVariant {
|
||||
descripcion?: string | null;
|
||||
precio?: string | number;
|
||||
values: Record<string, VariantAttributeValue>;
|
||||
}
|
||||
|
||||
interface VariantSelectorOption {
|
||||
key: string;
|
||||
value: VariantSelectionValue;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface VariantSelector {
|
||||
key: string;
|
||||
label: string;
|
||||
options: VariantSelectorOption[];
|
||||
}
|
||||
|
||||
@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,
|
||||
@@ -48,6 +24,7 @@ export class ProductVerticalWithCartCardComponent {
|
||||
readonly description = input<string>('');
|
||||
readonly price = input<number>(0);
|
||||
readonly variants = input<VerticalCartVariant[]>([]);
|
||||
readonly saving = input(false);
|
||||
|
||||
readonly quantity = model<number>(1);
|
||||
readonly selectedVariant = model<number | null>(null);
|
||||
@@ -55,8 +32,6 @@ 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, VariantSelectionValue>>({});
|
||||
|
||||
protected readonly selectedVariantData = computed(() =>
|
||||
this.variants().find((variant) => variant.id === this.selectedVariant()),
|
||||
);
|
||||
@@ -69,54 +44,13 @@ export class ProductVerticalWithCartCardComponent {
|
||||
return Number.isFinite(variantPrice) ? variantPrice : this.price();
|
||||
});
|
||||
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||
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: this.optionsFor(variants, key),
|
||||
}));
|
||||
});
|
||||
|
||||
protected readonly hasVariants = computed(() => this.variantSelectors().length > 0);
|
||||
|
||||
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(this.selectionValues(selected.values));
|
||||
this.selectedVariant.set(selected.id);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
protected onVariantValueChange(key: string, value: VariantSelectionValue): void {
|
||||
const values = { ...this.selectedValues(), [key]: value };
|
||||
const selectors = this.variantSelectors();
|
||||
const matchingVariant = this.variants().find((variant) =>
|
||||
selectors.every(
|
||||
(selector) =>
|
||||
this.valueKey(this.selectionValue(variant.values[selector.key])) ===
|
||||
this.valueKey(values[selector.key]),
|
||||
),
|
||||
);
|
||||
|
||||
this.selectedValues.set(values);
|
||||
this.selectedVariant.set(matchingVariant?.id ?? null);
|
||||
}
|
||||
protected readonly hasVariants = computed(() => this.variants().length > 0);
|
||||
|
||||
protected onAddToCart(): void {
|
||||
if (this.saving()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.addToCart.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
|
||||
}
|
||||
|
||||
@@ -124,60 +58,6 @@ export class ProductVerticalWithCartCardComponent {
|
||||
this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
|
||||
}
|
||||
|
||||
private optionsFor(variants: VerticalCartVariant[], key: string): VariantSelectorOption[] {
|
||||
const options = new Map<string, VariantSelectorOption>();
|
||||
|
||||
for (const variant of variants) {
|
||||
const attributeValue = variant.values[key];
|
||||
if (attributeValue === undefined) continue;
|
||||
|
||||
const value = this.selectionValue(attributeValue);
|
||||
const optionKey = this.valueKey(value);
|
||||
if (!options.has(optionKey)) {
|
||||
options.set(optionKey, {
|
||||
key: optionKey,
|
||||
value,
|
||||
label: this.selectionLabel(attributeValue),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(options.values());
|
||||
}
|
||||
|
||||
private selectionValues(
|
||||
values: Record<string, VariantAttributeValue>,
|
||||
): Record<string, VariantSelectionValue> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(values).map(([key, value]) => [key, this.selectionValue(value)]),
|
||||
);
|
||||
}
|
||||
|
||||
private selectionValue(value: VariantAttributeValue): VariantSelectionValue {
|
||||
if (typeof value === 'string') return value;
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => (typeof item === 'string' ? item : item.value));
|
||||
}
|
||||
return value.value;
|
||||
}
|
||||
|
||||
private selectionLabel(value: VariantAttributeValue): string {
|
||||
if (typeof value === 'string') return value;
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => (typeof item === 'string' ? item : item.label)).join(', ');
|
||||
}
|
||||
return value.label;
|
||||
}
|
||||
|
||||
private valueKey(value: VariantSelectionValue | undefined): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
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,7 +3,7 @@
|
||||
}
|
||||
|
||||
.quantity-selector {
|
||||
border: 1px solid #d8d8d8;
|
||||
border: 1px solid var(--border-color);
|
||||
width: 78px;
|
||||
height: 40px;
|
||||
min-height: 40px;
|
||||
@@ -39,15 +39,15 @@
|
||||
}
|
||||
|
||||
&--small {
|
||||
width: 46px;
|
||||
height: 21px;
|
||||
min-height: 21px;
|
||||
border: 1px solid #cfcfcf;
|
||||
width: 62px;
|
||||
height: 28px;
|
||||
min-height: 28px;
|
||||
border-color: var(--border-color);
|
||||
background-color: #ffffff;
|
||||
|
||||
.quantity-selector__button {
|
||||
width: 15px;
|
||||
font-size: 10px;
|
||||
width: 18px;
|
||||
font-size: 11px;
|
||||
background-color: #ffffff;
|
||||
color: #666666;
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
}
|
||||
|
||||
.quantity-selector__value {
|
||||
font-size: 10px;
|
||||
font-size: 11px;
|
||||
color: #666666;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,14 @@
|
||||
<select
|
||||
class="form-select variant-selector__select"
|
||||
[attr.aria-label]="selector.label"
|
||||
[disabled]="disabled()"
|
||||
[ngModel]="selectedValues()[selector.key]"
|
||||
[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>
|
||||
}
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
:host {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.variant-selector {
|
||||
display: flex;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.variant-selector__select {
|
||||
width: auto;
|
||||
min-width: 120px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
height: 38px;
|
||||
color: #666666;
|
||||
border-color: #cccccc;
|
||||
border-color: var(--border-color);
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
|
||||
@@ -24,15 +27,18 @@
|
||||
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 {
|
||||
justify-content: flex-end;
|
||||
gap: 4px;
|
||||
|
||||
.variant-selector__select {
|
||||
min-width: 0;
|
||||
max-width: 150px;
|
||||
max-width: none;
|
||||
height: 28px;
|
||||
padding: 0.2rem 1.75rem 0.2rem 0.45rem;
|
||||
font-size: 11px;
|
||||
|
||||
@@ -22,9 +22,9 @@ describe('VariantSelectorComponent', () => {
|
||||
}).compileComponents();
|
||||
const fixture = TestBed.createComponent(VariantSelectorComponent);
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{ value: 1, values: { alojamiento: 'Carpa', servicio: 'Almuerzo' } },
|
||||
{ value: 2, values: { alojamiento: 'Carpa', servicio: 'Cena' } },
|
||||
{ value: 3, values: { alojamiento: 'Hotel', servicio: 'Cena' } },
|
||||
{ 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();
|
||||
@@ -39,21 +39,99 @@ describe('VariantSelectorComponent', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('renders labels while matching variants by value', async () => {
|
||||
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', [
|
||||
{
|
||||
value: 1,
|
||||
values: { event_date: { value: '2', label: '10/10/2026' } },
|
||||
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();
|
||||
|
||||
const option = fixture.nativeElement.querySelector('option') as HTMLOptionElement;
|
||||
expect(option.textContent?.trim()).toBe('10/10/2026');
|
||||
expect((fixture.componentInstance as any).selectedValues()).toEqual({ event_date: '2' });
|
||||
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);
|
||||
});
|
||||
|
||||
it('clears every selected value when the reset token changes', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [VariantSelectorComponent],
|
||||
}).compileComponents();
|
||||
const fixture = TestBed.createComponent(VariantSelectorComponent);
|
||||
fixture.componentRef.setInput('variants', [{ id: 1, values: { sector: 'A', asiento: '1' } }]);
|
||||
fixture.componentRef.setInput('autoSelectFirst', false);
|
||||
fixture.detectChanges();
|
||||
|
||||
(fixture.componentInstance as any).onValueChange('sector', 'A');
|
||||
(fixture.componentInstance as any).onValueChange('asiento', '1');
|
||||
expect(fixture.componentInstance.selectedVariant()).toBe(1);
|
||||
|
||||
fixture.componentRef.setInput('resetToken', 1);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.componentInstance.selectedVariant()).toBeNull();
|
||||
expect((fixture.componentInstance as any).selectedValues()).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,23 +5,34 @@ import {
|
||||
effect,
|
||||
input,
|
||||
model,
|
||||
output,
|
||||
signal,
|
||||
untracked,
|
||||
} from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { VariantAttributeValue } from '../../../core/services/catalog/catalog.interface';
|
||||
|
||||
type VariantSelectionValue = string | string[];
|
||||
export interface VariantAttributeOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export type VariantAttributeScalar = string | VariantAttributeOption;
|
||||
export type VariantAttributeValue = VariantAttributeScalar | VariantAttributeScalar[];
|
||||
|
||||
export interface VariantSelectorVariant {
|
||||
value: unknown;
|
||||
id: unknown;
|
||||
values: Record<string, VariantAttributeValue>;
|
||||
}
|
||||
|
||||
export interface VariantSelectorSelectionChange {
|
||||
values: Record<string, VariantAttributeValue>;
|
||||
selectedVariant: unknown;
|
||||
}
|
||||
|
||||
interface VariantSelectorOption {
|
||||
key: string;
|
||||
label: string;
|
||||
value: VariantSelectionValue;
|
||||
value: VariantAttributeValue;
|
||||
}
|
||||
|
||||
interface VariantSelectorGroup {
|
||||
@@ -43,8 +54,15 @@ export class VariantSelectorComponent {
|
||||
readonly selectedVariant = model<unknown>(null);
|
||||
readonly disabled = input(false);
|
||||
readonly compact = input(false);
|
||||
readonly autoSelectFirst = input(true);
|
||||
readonly resetToken = input(0);
|
||||
readonly selectionValuesChange = output<VariantSelectorSelectionChange>();
|
||||
|
||||
protected readonly selectedValues = signal<Record<string, VariantSelectionValue>>({});
|
||||
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)))),
|
||||
);
|
||||
@@ -57,10 +75,7 @@ export class VariantSelectorComponent {
|
||||
const previousKeys = keys.slice(0, index);
|
||||
const compatibleVariants = variants.filter((variant) =>
|
||||
previousKeys.every((previousKey) =>
|
||||
this.sameValue(
|
||||
this.selectionValue(variant.values[previousKey]),
|
||||
selectedValues[previousKey],
|
||||
),
|
||||
this.sameValue(variant.values[previousKey], selectedValues[previousKey]),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -73,9 +88,31 @@ export class VariantSelectorComponent {
|
||||
});
|
||||
|
||||
constructor() {
|
||||
let initializedResetToken = false;
|
||||
let previousResetToken = 0;
|
||||
|
||||
effect(() => {
|
||||
const resetToken = this.resetToken();
|
||||
|
||||
untracked(() => {
|
||||
if (!initializedResetToken) {
|
||||
initializedResetToken = true;
|
||||
previousResetToken = resetToken;
|
||||
return;
|
||||
}
|
||||
|
||||
if (resetToken === previousResetToken) return;
|
||||
|
||||
previousResetToken = resetToken;
|
||||
this.selectedValues.set({});
|
||||
this.selectedVariant.set(null);
|
||||
});
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
const variants = this.variants();
|
||||
const selectedVariant = this.selectedVariant();
|
||||
const autoSelectFirst = this.autoSelectFirst();
|
||||
|
||||
untracked(() => {
|
||||
if (variants.length === 0) {
|
||||
@@ -84,64 +121,75 @@ export class VariantSelectorComponent {
|
||||
return;
|
||||
}
|
||||
|
||||
const selected =
|
||||
variants.find((variant) => Object.is(variant.value, selectedVariant)) ?? variants[0];
|
||||
this.selectedValues.set(this.selectionValues(selected.values));
|
||||
if (!Object.is(selected.value, selectedVariant)) this.selectedVariant.set(selected.value);
|
||||
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: VariantSelectionValue): void {
|
||||
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(), [key]: value };
|
||||
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(this.selectionValue(variant.values[previousKey]), values[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) values[currentKey] = firstOption.value;
|
||||
if (firstOption && this.autoSelectFirst()) values[currentKey] = firstOption.value;
|
||||
else delete values[currentKey];
|
||||
}
|
||||
}
|
||||
|
||||
const matchingVariant = variants.find((variant) =>
|
||||
keys.every((attributeKey) =>
|
||||
this.sameValue(this.selectionValue(variant.values[attributeKey]), values[attributeKey]),
|
||||
this.sameValue(variant.values[attributeKey], values[attributeKey]),
|
||||
),
|
||||
);
|
||||
|
||||
this.selectedValues.set(values);
|
||||
this.selectedVariant.set(matchingVariant?.value ?? null);
|
||||
this.selectedVariant.set(matchingVariant?.id ?? null);
|
||||
this.selectionValuesChange.emit({
|
||||
values: { ...values },
|
||||
selectedVariant: matchingVariant?.id ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
private optionsFor(variants: VariantSelectorVariant[], key: string): VariantSelectorOption[] {
|
||||
const options = new Map<string, VariantSelectorOption>();
|
||||
|
||||
for (const variant of variants) {
|
||||
const attributeValue = variant.values[key];
|
||||
if (attributeValue === undefined) continue;
|
||||
|
||||
const value = this.selectionValue(attributeValue);
|
||||
if (value === undefined || value === '' || (Array.isArray(value) && value.length === 0)) {
|
||||
continue;
|
||||
}
|
||||
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.selectionLabel(attributeValue),
|
||||
label: this.valueLabel(value),
|
||||
value,
|
||||
});
|
||||
}
|
||||
@@ -150,47 +198,56 @@ export class VariantSelectorComponent {
|
||||
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: VariantSelectionValue | undefined,
|
||||
right: VariantSelectionValue | undefined,
|
||||
left: VariantAttributeValue | undefined,
|
||||
right: VariantAttributeValue | undefined,
|
||||
): boolean {
|
||||
return (
|
||||
left !== undefined && right !== undefined && this.valueKey(left) === this.valueKey(right)
|
||||
);
|
||||
}
|
||||
|
||||
private valueKey(value: VariantSelectionValue): string {
|
||||
return JSON.stringify(value);
|
||||
private valueKey(value: VariantAttributeValue): string {
|
||||
const comparableValue = Array.isArray(value)
|
||||
? value.map((item) => this.scalarValue(item))
|
||||
: this.scalarValue(value);
|
||||
|
||||
return JSON.stringify(comparableValue);
|
||||
}
|
||||
|
||||
private selectionValues(
|
||||
values: Record<string, VariantAttributeValue>,
|
||||
): Record<string, VariantSelectionValue> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(values).flatMap(([key, value]) => {
|
||||
const selectionValue = this.selectionValue(value);
|
||||
return selectionValue === undefined ? [] : [[key, selectionValue]];
|
||||
}),
|
||||
);
|
||||
private valueLabel(value: VariantAttributeValue): string {
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
return values.map((item) => (typeof item === 'string' ? item : item.label)).join(', ');
|
||||
}
|
||||
|
||||
private selectionValue(
|
||||
value: VariantAttributeValue | undefined,
|
||||
): VariantSelectionValue | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
if (typeof value === 'string') return value;
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => (typeof item === 'string' ? item : item.value));
|
||||
}
|
||||
return value.value;
|
||||
}
|
||||
|
||||
private selectionLabel(value: VariantAttributeValue): string {
|
||||
if (typeof value === 'string') return value;
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => (typeof item === 'string' ? item : item.label)).join(', ');
|
||||
}
|
||||
return value.label;
|
||||
private scalarValue(value: VariantAttributeScalar): string {
|
||||
return typeof value === 'string' ? value : value.value;
|
||||
}
|
||||
|
||||
private formatVariantLabel(key: string): string {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user