Compare commits

...

10 Commits

27 changed files with 1539 additions and 172 deletions

2
.vscode/launch.json vendored
View File

@@ -7,7 +7,7 @@
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
"url": "http://localhost:4300/"
},
{
"name": "ng test",

View File

@@ -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"

View 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);
});
});

View File

@@ -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,
)
);
}

View File

@@ -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));

View 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);
});
});

View File

@@ -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;
}

View File

@@ -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';
@@ -181,6 +183,43 @@ describe('AuthService', () => {
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: [

View File

@@ -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,6 +20,7 @@ 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.front.auth.token';
const AUTH_USER_SSR_STATE_KEY = makeStateKey<AuthUser>('shopit.auth.user');
@@ -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);

View 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,
},
);

View File

@@ -118,11 +118,23 @@ export interface CatalogFeaturedItemVariant {
}
export interface CatalogVariantOptionsResponse {
variants: CatalogFeaturedItemVariant[];
options: Record<string, CatalogVariantValue[]>;
selectors: CatalogVariantSelector[];
selected_values: Record<string, string | string[]>;
resolved_variant_id: number | null;
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 {

View File

@@ -92,7 +92,6 @@ export class CatalogService extends BaseApiService {
catalogItemId: number,
payload: {
selected_values: Record<string, string | string[]>;
excluded_variant_ids?: number[];
cart_item_id?: number | null;
},
): Observable<CatalogVariantOptionsResponse> {

View File

@@ -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();
}
});
});

View File

@@ -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);

View File

@@ -767,11 +767,11 @@
</p>
<app-product-ticket-selector
[productId]="1"
[title]="testTicketSelectorProduct.title"
[description]="testTicketSelectorProduct.description"
[price]="testTicketSelectorProduct.price"
[imageUrl]="testTicketSelectorProduct.imageUrl"
[variants]="testTicketSelectorProduct.variants"
(buy)="onTicketBuy($event)"
/>
</div>

View File

@@ -113,7 +113,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,15 +128,25 @@ export class CategoryItemsPageComponent {
this.creatingDirectPurchase.set(true);
try {
const purchase = await this.injector.get(CheckoutService).startCheckout(tenant.codigo, {
direct_items: [
{
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);

View File

@@ -145,7 +145,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,15 +160,25 @@ export class SearchPageComponent {
this.creatingDirectPurchase.set(true);
try {
const purchase = await this.injector.get(CheckoutService).startCheckout(tenant.codigo, {
direct_items: [
{
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);

View File

@@ -169,7 +169,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;
}
@@ -183,6 +185,11 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
this.creatingDirectPurchase.set(true);
try {
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
@@ -198,9 +205,10 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
cantidad: event.quantity,
},
];
const purchase = await checkoutService.startCheckout(tenant.codigo, {
direct_items: directItems,
});
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);

View File

@@ -29,12 +29,11 @@
}
@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"
[variants]="item.variants ?? []"
[unavailableVariantIds]="unavailableVariantIds()"
[disabled]="loading()"
(buy)="emitTicketBuy(item, $event)"
/>

View File

@@ -1,8 +1,11 @@
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,
@@ -51,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);
@@ -265,7 +290,12 @@ describe('ProductListComponent', () => {
const ticketSelector = fixture.debugElement.query(By.directive(ProductTicketSelectorComponent))
.componentInstance as ProductTicketSelectorComponent;
ticketSelector['updateRow'](1, 401);
ticketSelector['patchRow'](1, {
variantId: 401,
reservedVariantId: 401,
cartItemId: 1,
status: 'reserved',
});
fixture.detectChanges();
(element.querySelector('.ticket-selector__add-row-button') as HTMLButtonElement).click();
@@ -274,7 +304,12 @@ describe('ProductListComponent', () => {
expect(element.querySelectorAll('.ticket-selector__row')).toHaveLength(2);
expect(element.querySelectorAll('.variant-selector__select')).toHaveLength(8);
ticketSelector['updateRow'](2, 402);
ticketSelector['patchRow'](2, {
variantId: 402,
reservedVariantId: 402,
cartItemId: 2,
status: 'reserved',
});
fixture.detectChanges();
(element.querySelector('.ticket-selector__actions .btn-primary') as HTMLButtonElement).click();
@@ -285,26 +320,24 @@ describe('ProductListComponent', () => {
variant: 401,
variantIds: [401, 402],
directPurchase: true,
reservedInCart: true,
});
});
it('removes unavailable variants from the ticket selector', async () => {
it('loads ticket selector availability without requiring catalog variants', async () => {
const ticket: ProductListItem = {
...items[0],
variants: [
{ id: 401, stock_tecnico: 1, values: { asiento: { value: '1', label: '1' } } },
{ id: 402, stock_tecnico: 1, values: { asiento: { value: '2', label: '2' } } },
],
variants: undefined,
};
const fixture = await render('ticket_selector', [ticket], 'single');
fixture.componentRef.setInput('unavailableVariantIds', new Set([401]));
await fixture.whenStable();
fixture.detectChanges();
const selector = fixture.debugElement.query(By.directive(ProductTicketSelectorComponent))
.componentInstance as ProductTicketSelectorComponent;
expect(selector['selectableVariants']().map((variant) => variant.id)).toEqual([402]);
expect(selector['availableVariantCount']()).toBe(2);
expect(fixture.nativeElement.querySelectorAll('.variant-selector__select')).toHaveLength(4);
});
it('renders carousel groups with the reusable carousel', async () => {

View File

@@ -41,6 +41,7 @@ export interface ProductListBuyEvent {
variant?: number | null;
variantIds?: number[];
directPurchase: boolean;
reservedInCart?: boolean;
}
@Component({
@@ -159,6 +160,7 @@ export class ProductListComponent {
variant: variantIds[0] ?? null,
variantIds,
directPurchase: true,
reservedInCart: true,
});
}
}

View File

@@ -17,23 +17,55 @@
</header>
<div class="ticket-selector__selection">
<span class="ticket-selector__label">Seleccioná Entrada/s:</span>
<div class="ticket-selector__label-row">
<span class="ticket-selector__label">Seleccioná Entrada/s:</span>
@if (validationStatus(); as status) {
<span
class="ticket-selector__validation ticket-selector__validation--{{ status }}"
role="status"
aria-live="polite"
>
@switch (status) {
@case ('validating') {
<span class="ticket-selector__validation-spinner" aria-hidden="true"></span>
Validando
}
@case ('validated') {
<i class="fa-solid fa-check" aria-hidden="true"></i>
Validado
}
@case ('error') {
<i class="fa-solid fa-xmark" aria-hidden="true"></i>
Error
}
}
</span>
}
</div>
<div class="ticket-selector__rows">
@for (row of rows(); track row.id) {
<div class="ticket-selector__row">
<app-variant-selector
class="ticket-selector__fields"
[variants]="variantsForRow(row.id)"
[disabled]="disabled()"
[autoSelectFirst]="false"
[selectedVariant]="row.variantId"
(selectedVariantChange)="updateRow(row.id, $event)"
/>
<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"
[value]="selectedOptionKey(row, selector.key)"
(change)="onSelectionKeyChange(row.id, selector, $any($event.target).value)"
>
<option value="" disabled>Seleccioná {{ selector.label }}</option>
@for (option of selector.options; track $index) {
<option [value]="optionKey(option)">{{ optionLabel(option) }}</option>
}
</select>
}
</div>
<app-icon-button
variant="trash"
ariaLabel="Eliminar entrada"
[disabled]="disabled()"
[disabled]="rowDisabled(row)"
(clicked)="removeRow(row.id)"
/>
</div>
@@ -50,7 +82,7 @@
+ Agregar entrada
</app-button>
@if (selectableVariants().length === 0) {
@if (availableVariantCount() === 0) {
<p class="ticket-selector__empty">No hay entradas disponibles.</p>
}

View File

@@ -44,14 +44,49 @@
padding-top: 1rem;
}
&__label {
display: block;
&__label-row {
display: flex;
align-items: center;
gap: 0.65rem;
min-height: 1.5rem;
margin-bottom: 0.5rem;
}
&__label {
color: #555;
font-size: 15px;
font-weight: 700;
}
&__validation {
display: inline-flex;
align-items: center;
gap: 0.3rem;
font-size: 13px;
font-weight: 600;
&--validating {
color: #777;
}
&--validated {
color: var(--success-color, #198754);
}
&--error {
color: var(--danger-color, #dc3545);
}
}
&__validation-spinner {
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;
}
&__rows {
display: grid;
gap: 0.5rem;
@@ -66,11 +101,23 @@
&__fields {
min-width: 0;
display: grid;
grid-template-columns: repeat(4, minmax(120px, 1fr));
gap: 0.5rem;
}
::ng-deep .variant-selector {
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);
}
}
@@ -103,6 +150,18 @@
}
}
@keyframes ticket-selector-spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.ticket-selector__validation-spinner {
animation-duration: 1.4s;
}
}
@media (max-width: 767.98px) {
.ticket-selector {
&__header {
@@ -110,9 +169,7 @@
}
&__fields {
::ng-deep .variant-selector {
grid-template-columns: 1fr;
}
grid-template-columns: 1fr;
}
&__map {

View File

@@ -0,0 +1,433 @@
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, 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';
describe('ProductTicketSelectorComponent', () => {
beforeAll(() => {
try {
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
} catch {
// Test environment may already be initialized by another setup entrypoint.
}
});
afterEach(() => TestBed.resetTestingModule());
it('checks partial selections and reserves the resolved variant in the cart', async () => {
const openConfirmDelete = vi.fn().mockReturnValue(of(true));
const removeItem = vi.fn().mockReturnValue(
of({
data: {
id: 10,
tenant_codigo: 'demo',
status: 'active',
subtotal: '0.00',
items: [],
},
}),
);
const resolvedVariant = {
id: 401,
precio: '10000.00',
stock_tecnico: 1,
values: { sector: { value: 'a', label: 'Sector A' }, seat: '1' },
};
const summary = {
valid: true,
available_variant_count: 1,
matching_variant_count: 1,
price_range: { minimum: '10000.00', maximum: '10000.00' },
};
const catalogService = {
withoutLoading: vi.fn(),
getVariantOptions: vi
.fn()
.mockReturnValueOnce(
of({
...summary,
selectors: [
{
key: 'sector',
label: 'Sector',
options: [{ value: 'a', label: 'Sector A' }],
enabled: true,
},
{ key: 'seat', label: 'Seat', options: ['1'], enabled: false },
],
selected_values: {},
resolved_variant: null,
}),
)
.mockReturnValueOnce(
of({
...summary,
selectors: [
{
key: 'sector',
label: 'Sector',
options: [{ value: 'a', label: 'Sector A' }],
enabled: true,
},
{ key: 'seat', label: 'Seat', options: ['1'], enabled: true },
],
selected_values: { sector: 'a' },
resolved_variant: null,
}),
)
.mockReturnValueOnce(
of({
...summary,
selectors: [],
selected_values: { sector: 'a', seat: '1' },
resolved_variant: resolvedVariant,
}),
),
};
const cartService = {
cart: signal(null).asReadonly(),
withoutLoading: vi.fn(),
addItem: vi.fn().mockReturnValue(
of({
data: {
id: 10,
tenant_codigo: 'demo',
status: 'active',
subtotal: '10000.00',
items: [
{
id: 25,
cantidad: 1,
precio_unitario: '10000.00',
catalog_item_id: 7,
variant_id: 401,
product: null,
},
],
},
}),
),
removeItem,
};
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 } },
],
}).compileComponents();
const fixture = TestBed.createComponent(ProductTicketSelectorComponent);
fixture.componentRef.setInput('productId', 7);
fixture.componentRef.setInput('title', 'Entrada');
fixture.detectChanges();
await fixture.whenStable();
expect(catalogService.getVariantOptions).toHaveBeenCalledTimes(1);
expect(catalogService.withoutLoading).toHaveBeenCalled();
fixture.componentInstance['onSelectionChange'](1, 'sector', {
value: 'a',
label: 'Sector A',
});
expect(catalogService.getVariantOptions).toHaveBeenLastCalledWith(7, {
selected_values: { sector: 'a' },
cart_item_id: null,
});
expect(fixture.componentInstance['rows']()[0].status).toBe('selecting');
fixture.componentInstance['onSelectionChange'](1, 'seat', '1');
expect(cartService.addItem).toHaveBeenCalledWith(7, 401, 1);
expect(cartService.withoutLoading).toHaveBeenCalled();
expect(fixture.componentInstance['rows']()[0]).toMatchObject({
variantId: 401,
reservedVariantId: 401,
cartItemId: 25,
status: 'reserved',
});
fixture.detectChanges();
const validation = fixture.nativeElement.querySelector('.ticket-selector__validation');
expect(validation.textContent).toContain('Validado');
expect(validation.querySelector('.fa-check')).not.toBeNull();
expect(fixture.nativeElement.querySelector('.ticket-selector__row-status')).toBeNull();
expect(fixture.nativeElement.querySelector('.ticket-selector__row-error')).toBeNull();
const deleteButton = fixture.nativeElement.querySelector(
'app-icon-button button',
) as HTMLButtonElement;
expect(deleteButton.classList.contains('icon-btn--bordered')).toBe(true);
deleteButton.click();
expect(openConfirmDelete).toHaveBeenCalledWith({
title: 'Eliminar entrada',
content:
'Se eliminará esta entrada de “Entrada”. Si ya estaba reservada, se liberará del carrito.',
confirmLabel: 'Sí, eliminar',
cancelLabel: 'Cancelar',
size: 'md',
});
expect(removeItem).toHaveBeenCalledWith(25);
expect(fixture.componentInstance['rows']()).toHaveLength(0);
});
it('restores selections that are already reserved in the cart', async () => {
const cartState = signal({
id: 10,
tenant_codigo: 'demo',
status: 'active',
subtotal: '10000.00',
items: [
{
id: 25,
cantidad: 1,
precio_unitario: '10000.00',
catalog_item_id: 7,
variant_id: 401,
product: {
nombre: 'Entrada',
imagen: null,
variants: [
{
id: 401,
precio: '10000.00',
stock_tecnico: 1,
values: {
sector: { value: 'a', label: 'Sector A' },
seat: '1',
},
},
],
},
},
],
});
const catalogService = {
withoutLoading: vi.fn(),
getVariantOptions: vi.fn().mockReturnValue(
of({
valid: true,
available_variant_count: 1,
matching_variant_count: 1,
price_range: { minimum: '10000.00', maximum: '10000.00' },
selectors: [
{
key: 'sector',
label: 'Sector',
options: [{ value: 'a', label: 'Sector A' }],
enabled: true,
},
{ key: 'seat', label: 'Seat', options: ['1'], enabled: true },
],
selected_values: { sector: 'a', seat: '1' },
resolved_variant: {
id: 401,
precio: '10000.00',
stock_tecnico: 1,
values: { sector: { value: 'a', label: 'Sector A' }, seat: '1' },
},
}),
),
};
const cartService = {
cart: cartState.asReadonly(),
withoutLoading: vi.fn(),
addItem: vi.fn(),
updateItemVariant: vi.fn(),
};
catalogService.withoutLoading.mockReturnValue(catalogService);
cartService.withoutLoading.mockReturnValue(cartService);
await TestBed.configureTestingModule({
imports: [ProductTicketSelectorComponent],
providers: [
{ provide: CatalogService, useValue: catalogService },
{ provide: CartService, useValue: cartService },
],
}).compileComponents();
const fixture = TestBed.createComponent(ProductTicketSelectorComponent);
fixture.componentRef.setInput('productId', 7);
fixture.componentRef.setInput('title', 'Entrada');
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(catalogService.getVariantOptions).toHaveBeenCalledWith(7, {
selected_values: { sector: 'a', seat: '1' },
cart_item_id: 25,
});
expect(fixture.componentInstance['rows']()[0]).toMatchObject({
variantId: 401,
reservedVariantId: 401,
cartItemId: 25,
selectedValues: { sector: 'a', seat: '1' },
status: 'reserved',
});
expect(cartService.addItem).not.toHaveBeenCalled();
expect(cartService.updateItemVariant).not.toHaveBeenCalled();
const selects = Array.from<HTMLSelectElement>(fixture.nativeElement.querySelectorAll('select'));
expect(selects.map((select) => select.selectedOptions[0]?.textContent?.trim())).toEqual([
'Sector A',
'1',
]);
expect(
fixture.nativeElement.querySelector('.ticket-selector__validation').textContent,
).toContain('Validado');
});
it('keeps the reserved selection and shows a toast when a variant change cannot be completed', async () => {
const cartState = signal({
id: 10,
tenant_codigo: 'demo',
status: 'active',
subtotal: '10000.00',
items: [
{
id: 25,
cantidad: 1,
precio_unitario: '10000.00',
catalog_item_id: 7,
variant_id: 401,
product: {
nombre: 'Entrada',
imagen: null,
variants: [
{
id: 401,
precio: '10000.00',
stock_tecnico: 0,
values: { seat: '1' },
},
],
},
},
],
});
const selector = {
key: 'seat',
label: 'Asiento',
options: ['1', '2'],
enabled: true,
};
const summary = {
valid: true,
available_variant_count: 2,
matching_variant_count: 1,
price_range: { minimum: '10000.00', maximum: '10000.00' },
selectors: [selector],
};
const catalogService = {
withoutLoading: vi.fn(),
getVariantOptions: vi
.fn()
.mockReturnValueOnce(
of({
...summary,
selected_values: { seat: '1' },
resolved_variant: {
id: 401,
precio: '10000.00',
stock_tecnico: 0,
values: { seat: '1' },
},
}),
)
.mockReturnValueOnce(
of({
...summary,
selected_values: { seat: '2' },
resolved_variant: {
id: 402,
precio: '10000.00',
stock_tecnico: 1,
values: { seat: '2' },
},
}),
),
};
const errorMessage = 'La entrada seleccionada ya no está disponible.';
const cartService = {
cart: cartState.asReadonly(),
withoutLoading: vi.fn(),
updateItemVariant: vi.fn().mockReturnValue(
throwError(
() =>
new HttpErrorResponse({
status: 422,
error: { message: errorMessage },
}),
),
),
};
const toastService = { danger: vi.fn() };
catalogService.withoutLoading.mockReturnValue(catalogService);
cartService.withoutLoading.mockReturnValue(cartService);
await TestBed.configureTestingModule({
imports: [ProductTicketSelectorComponent],
providers: [
{ provide: CatalogService, useValue: catalogService },
{ provide: CartService, useValue: cartService },
{ provide: ToastService, useValue: toastService },
],
}).compileComponents();
const fixture = TestBed.createComponent(ProductTicketSelectorComponent);
fixture.componentRef.setInput('productId', 7);
fixture.componentRef.setInput('title', 'Entrada');
fixture.detectChanges();
await fixture.whenStable();
fixture.componentInstance['onSelectionChange'](1, 'seat', '2');
fixture.detectChanges();
expect(cartService.updateItemVariant).toHaveBeenCalledWith(25, 1, 402);
expect(toastService.danger).toHaveBeenCalledWith(errorMessage);
expect(fixture.componentInstance['rows']()[0]).toMatchObject({
variantId: 401,
reservedVariantId: 401,
selectedValues: { seat: '1' },
status: 'reserved',
error: null,
});
const select = fixture.nativeElement.querySelector('select') as HTMLSelectElement;
expect(select.value).toBe(JSON.stringify('1'));
const unavailableMessage = 'La combinación seleccionada ya no está disponible.';
catalogService.getVariantOptions.mockReturnValueOnce(
of({
...summary,
valid: false,
matching_variant_count: 0,
selected_values: {},
resolved_variant: null,
}),
);
fixture.componentInstance['onSelectionChange'](1, 'seat', '2');
fixture.detectChanges();
expect(cartService.updateItemVariant).toHaveBeenCalledTimes(1);
expect(toastService.danger).toHaveBeenLastCalledWith(unavailableMessage);
expect(fixture.componentInstance['rows']()[0]).toMatchObject({
variantId: 401,
reservedVariantId: 401,
selectedValues: { seat: '1' },
status: 'reserved',
error: null,
});
expect(select.value).toBe(JSON.stringify('1'));
});
});

View File

@@ -1,76 +1,117 @@
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 { CartService } from '../../../core/services/cart/cart.service';
import { CartItem, CartItemVariantValue } from '../../../core/services/cart/cart.interface';
import { ModalService } from '../../../core/services/modal.service';
import { ToastService } from '../../../core/services/toast.service';
import {
CatalogVariantOptionsResponse,
CatalogVariantSelector,
CatalogVariantValue,
} from '../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../core/services/catalog/catalog.service';
import { ButtonComponent } from '../button/button.component';
import { IconButtonComponent } from '../icon-button/icon-button.component';
import {
VariantSelectorComponent,
VariantSelectorVariant,
} from '../variant-selector/variant-selector.component';
export interface TicketSelectorVariant extends VariantSelectorVariant {
precio?: string | number;
stock_tecnico?: number | null;
}
type TicketSelectionStatus =
| 'selecting'
| 'checking'
| 'reserving'
| 'reserved'
| 'removing'
| 'error';
type TicketValidationStatus = 'validating' | 'validated' | 'error';
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[]>;
reservedSelectors: CatalogVariantSelector[];
status: TicketSelectionStatus;
error: string | null;
}
@Component({
selector: 'app-product-ticket-selector',
imports: [ButtonComponent, IconButtonComponent, VariantSelectorComponent],
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 optionRequests = new Map<number, Subscription>();
private readonly reservationRequests = new Map<number, Subscription>();
private readonly viewReady = signal(false);
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 variants = input<TicketSelectorVariant[]>([]);
readonly unavailableVariantIds = input<ReadonlySet<number>>(new Set<number>());
readonly disabled = input(false);
readonly buy = output<number[]>();
protected readonly rows = signal<TicketSelectionRow[]>([{ id: 1, variantId: null }]);
protected readonly rows = signal<TicketSelectionRow[]>([this.createRow(1)]);
protected readonly availableVariantCount = signal(0);
private readonly remotePriceRange = signal<{ minimum: number; maximum: number } | null>(null);
private nextRowId = 2;
protected readonly selectableVariants = computed<TicketSelectorVariant[]>(() =>
this.variants().filter(
(variant) =>
!this.unavailableVariantIds().has(variant.id as number) &&
(variant.stock_tecnico == null || variant.stock_tecnico > 0),
),
);
protected readonly hasSelection = computed(
() => this.rows().length > 0 && this.rows().every((row) => row.variantId !== null),
() =>
this.rows().length > 0 &&
this.rows().every(
(row) =>
row.status === 'reserved' &&
row.variantId !== null &&
row.variantId === row.reservedVariantId,
),
);
protected readonly validationStatus = computed<TicketValidationStatus | null>(() => {
const rows = this.rows();
if (rows.some((row) => this.isBusy(row))) return 'validating';
if (rows.some((row) => row.status === 'error' || row.error !== null)) return 'error';
if (rows.length > 0 && rows.every((row) => row.status === 'reserved')) return 'validated';
return null;
});
protected readonly canAddRow = computed(
() => this.rows().length < this.selectableVariants().length,
() =>
this.availableVariantCount() > 0 &&
this.rows().every((row) => row.status === 'reserved') &&
!this.rows().some((row) => this.isBusy(row)),
);
protected readonly priceRange = computed(() => {
const prices = this.selectableVariants()
.map((variant) => Number(variant.precio ?? this.price()))
.filter(Number.isFinite);
const range = this.remotePriceRange();
const minimum = range?.minimum ?? this.price();
const maximum = range?.maximum ?? this.price();
if (prices.length === 0) {
const price = this.formatCurrency(this.price());
return { minimum: price, maximum: price, hasRange: false };
}
const minimum = Math.min(...prices);
const maximum = Math.max(...prices);
return {
minimum: this.formatCurrency(minimum),
maximum: this.formatCurrency(maximum),
@@ -80,56 +121,492 @@ export class ProductTicketSelectorComponent {
constructor() {
effect(() => {
const unavailable = this.unavailableVariantIds();
const viewReady = this.viewReady();
const cart = this.cartService.cart?.() ?? null;
if (!this.rows().some((row) => row.variantId !== null && unavailable.has(row.variantId))) {
return;
}
if (!viewReady) return;
this.rows.update((rows) =>
rows.map((row) =>
row.variantId !== null && unavailable.has(row.variantId)
? { ...row, variantId: null }
: row,
),
);
untracked(() => {
if (cart === null) {
this.ensureEmptyRowLoaded();
return;
}
this.synchronizeWithCart(cart.items);
});
});
afterNextRender(() => this.viewReady.set(true));
this.destroyRef.onDestroy(() => {
this.optionRequests.forEach((request) => request.unsubscribe());
this.reservationRequests.forEach((request) => request.unsubscribe());
});
}
protected onBuy(): void {
const variantIds = this.rows().flatMap((row) =>
row.variantId === null ? [] : [row.variantId],
row.reservedVariantId === null ? [] : [row.reservedVariantId],
);
if (variantIds.length === this.rows().length && variantIds.length > 0) {
if (this.hasSelection() && variantIds.length > 0) {
this.buy.emit(variantIds);
}
}
protected addRow(): void {
if (!this.canAddRow()) return;
this.rows.update((rows) => [...rows, { id: this.nextRowId++, variantId: null }]);
const row = this.createRow(this.nextRowId++);
this.rows.update((rows) => [...rows, row]);
this.loadOptions(row.id, {});
}
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 {
const rowId = row.id;
this.optionRequests.get(rowId)?.unsubscribe();
if (row.cartItemId === null) {
this.deleteRow(rowId);
return;
}
this.patchRow(rowId, { status: 'removing', error: null });
const request = this.cartService
.withoutLoading()
.removeItem(row.cartItemId)
.subscribe({
next: () => {
this.availableVariantCount.update((count) => count + 1);
this.deleteRow(rowId);
},
error: (error: HttpErrorResponse) => {
this.patchRow(rowId, {
status: 'reserved',
error: this.errorMessage(error, 'No se pudo liberar la entrada.'),
});
},
});
this.reservationRequests.set(rowId, request);
}
protected onSelectionChange(
rowId: number,
selectorKey: string,
value: CatalogVariantValue | null,
): void {
const row = this.findRow(rowId);
if (!row || this.isBusy(row)) return;
const selectorIndex = row.selectors.findIndex((selector) => selector.key === selectorKey);
const retainedKeys = new Set(row.selectors.slice(0, selectorIndex + 1).map(({ key }) => key));
const selectedValues = Object.fromEntries(
Object.entries(row.selectedValues).filter(([key]) => retainedKeys.has(key)),
);
if (value === null) delete selectedValues[selectorKey];
else selectedValues[selectorKey] = this.normalizeValue(value);
const preservesReservedSelection =
row.reservedVariantId !== null &&
row.selectors.length > 0 &&
row.selectors.every(({ key }) => key in selectedValues);
this.loadOptions(rowId, selectedValues, preservesReservedSelection);
}
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 loadOptions(
rowId: number,
selectedValues: Record<string, string | string[]>,
preserveReservedSelection = false,
): void {
const row = this.findRow(rowId);
if (!row) return;
this.optionRequests.get(rowId)?.unsubscribe();
this.patchRow(rowId, {
selectedValues: preserveReservedSelection ? row.reservedSelectedValues : selectedValues,
status: 'checking',
error: null,
});
const request = this.catalogService
.withoutLoading()
.getVariantOptions(this.productId(), {
selected_values: selectedValues,
cart_item_id: row.cartItemId,
})
.subscribe({
next: (response) => {
this.applySummary(response, row);
if (!response.valid) {
if (row.reservedVariantId !== null) {
this.restoreReservedRowAfterError(
rowId,
row,
'La combinación seleccionada ya no está disponible.',
);
return;
}
this.patchRow(rowId, {
variantId: null,
selectedValues: {},
selectors: response.selectors,
status: response.available_variant_count === 0 ? 'selecting' : 'error',
error:
response.available_variant_count === 0
? null
: 'La combinación seleccionada ya no está disponible.',
});
return;
}
this.patchRow(rowId, {
variantId: response.resolved_variant?.id ?? null,
selectedValues: preserveReservedSelection
? row.reservedSelectedValues
: response.selected_values,
selectors: preserveReservedSelection ? row.reservedSelectors : response.selectors,
status: 'selecting',
error: null,
});
if (response.resolved_variant !== null) {
if (row.cartItemId !== null && row.reservedVariantId === response.resolved_variant.id) {
this.patchRow(rowId, {
reservedSelectedValues: response.selected_values,
reservedSelectors: response.selectors,
status: 'reserved',
});
} else {
this.reserveRow(
rowId,
response.resolved_variant.id,
response.selected_values,
response.selectors,
);
}
}
},
error: (error: HttpErrorResponse) => {
const message = this.errorMessage(error, 'No se pudo consultar la disponibilidad.');
if (row.reservedVariantId !== null) {
this.restoreReservedRowAfterError(rowId, row, message);
return;
}
this.patchRow(rowId, { status: 'error', error: message });
this.toastService.danger(message);
},
});
this.optionRequests.set(rowId, request);
}
private reserveRow(
rowId: number,
variantId: number,
selectedValues: Record<string, string | string[]>,
selectors: CatalogVariantSelector[],
): void {
const row = this.findRow(rowId);
if (!row || (row.status === 'reserved' && row.reservedVariantId === variantId)) return;
this.patchRow(rowId, {
selectedValues: row.reservedVariantId === null ? selectedValues : row.reservedSelectedValues,
selectors: row.reservedVariantId === null ? selectors : row.reservedSelectors,
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;
}
this.patchRow(rowId, {
variantId,
reservedVariantId: variantId,
selectedValues,
selectors,
reservedSelectedValues: selectedValues,
reservedSelectors: selectors,
cartItemId: cartItem.id,
status: 'reserved',
error: null,
});
if (row.cartItemId === null) {
this.availableVariantCount.update((count) => Math.max(0, count - 1));
}
},
error: (error: HttpErrorResponse) => {
const message = this.errorMessage(error, 'La entrada ya no está disponible.');
if (row.reservedVariantId !== null) {
this.restoreReservedRowAfterError(rowId, row, message);
return;
}
this.patchRow(rowId, { variantId: null, status: 'error', error: message });
this.toastService.danger(message);
},
});
this.reservationRequests.set(rowId, request);
}
private restoreReservedRowAfterError(
rowId: number,
row: TicketSelectionRow,
message: string,
): void {
this.patchRow(rowId, {
variantId: row.reservedVariantId,
selectedValues: row.reservedSelectedValues,
selectors: row.reservedSelectors,
status: 'reserved',
error: null,
});
this.toastService.danger(message);
}
private applySummary(response: CatalogVariantOptionsResponse, row: TicketSelectionRow): void {
this.availableVariantCount.set(
Math.max(0, response.available_variant_count - (row.cartItemId === null ? 0 : 1)),
);
this.remotePriceRange.set({
minimum: Number(response.price_range.minimum),
maximum: Number(response.price_range.maximum),
});
}
private createRow(id: number): TicketSelectionRow {
return {
id,
variantId: null,
reservedVariantId: null,
cartItemId: null,
selectedValues: {},
selectors: [],
reservedSelectedValues: {},
reservedSelectors: [],
status: 'checking',
error: null,
};
}
private createCartRow(item: CartItem, id = this.nextRowId++): TicketSelectionRow | null {
if (item.variant_id === null) return null;
const variant = item.product?.variants?.find(({ id }) => id === item.variant_id);
if (!variant) return null;
const selectedValues = this.normalizeCartValues(variant.values);
return {
id,
variantId: item.variant_id,
reservedVariantId: item.variant_id,
cartItemId: item.id,
selectedValues,
selectors: [],
reservedSelectedValues: selectedValues,
reservedSelectors: [],
status: 'checking',
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) {
if (currentRows.some((row) => row.cartItemId !== null)) {
this.replaceRows([this.createRow(this.nextRowId++)]);
}
this.ensureEmptyRowLoaded();
return;
}
const rowsToLoad: TicketSelectionRow[] = [];
const synchronizedRows = cartItems.flatMap((item) => {
const existingRow = currentRows.find((row) => row.cartItemId === item.id);
const cartRow = this.createCartRow(item, existingRow?.id);
if (!cartRow) return [];
if (
existingRow &&
existingRow.reservedVariantId === cartRow.reservedVariantId &&
this.sameSelectedValues(existingRow.selectedValues, cartRow.selectedValues)
) {
return [existingRow];
}
rowsToLoad.push(cartRow);
return [cartRow];
});
const localRows = currentRows.filter(
(row) => row.cartItemId === null && Object.keys(row.selectedValues).length > 0,
);
this.replaceRows([...synchronizedRows, ...localRows]);
rowsToLoad.forEach((row) => this.loadOptions(row.id, row.selectedValues));
}
private ensureEmptyRowLoaded(): void {
const currentRows = this.rows();
if (currentRows.length === 0) {
const row = this.createRow(this.nextRowId++);
this.rows.set([row]);
this.loadOptions(row.id, {});
return;
}
if (currentRows.length === 1 && !this.optionRequests.has(currentRows[0].id)) {
this.loadOptions(currentRows[0].id, currentRows[0].selectedValues);
}
}
private replaceRows(rows: TicketSelectionRow[]): void {
const retainedIds = new Set(rows.map(({ id }) => id));
this.rows().forEach((row) => {
if (retainedIds.has(row.id)) return;
this.optionRequests.get(row.id)?.unsubscribe();
this.reservationRequests.get(row.id)?.unsubscribe();
this.optionRequests.delete(row.id);
this.reservationRequests.delete(row.id);
});
this.rows.set(rows);
}
private normalizeCartValues(
values: Record<string, CartItemVariantValue>,
): Record<string, string | string[]> {
return Object.fromEntries(
Object.entries(values).map(([key, value]) => [key, this.normalizeValue(value)]),
);
}
private sameSelectedValues(
left: Record<string, string | string[]>,
right: Record<string, string | string[]>,
): boolean {
return JSON.stringify(left) === JSON.stringify(right);
}
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.optionRequests.delete(rowId);
this.reservationRequests.delete(rowId);
}
protected updateRow(rowId: number, selectedVariant: unknown): void {
const variantId = typeof selectedVariant === 'number' ? selectedVariant : null;
this.rows.update((rows) => rows.map((row) => (row.id === rowId ? { ...row, variantId } : row)));
private isBusy(row: TicketSelectionRow): boolean {
return ['checking', 'reserving', 'removing'].includes(row.status);
}
protected variantsForRow(rowId: number): VariantSelectorVariant[] {
const selectedByOtherRows = new Set(
this.rows()
.filter((row) => row.id !== rowId && row.variantId !== null)
.map((row) => row.variantId),
);
private normalizeValue(value: CatalogVariantValue): string | string[] {
return Array.isArray(value)
? value.map((item) => this.scalarValue(item))
: this.scalarValue(value);
}
return this.selectableVariants().filter(
(variant) => !selectedByOtherRows.has(variant.id as number),
);
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 {

View File

@@ -114,4 +114,24 @@ describe('VariantSelectorComponent', () => {
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({});
});
});

View File

@@ -55,6 +55,7 @@ export class VariantSelectorComponent {
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, VariantAttributeValue>>({});
@@ -87,6 +88,27 @@ 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();