Compare commits
44 Commits
0defe75adb
...
fix/expira
| Author | SHA1 | Date | |
|---|---|---|---|
| 4251ca8a8a | |||
| cfa1091116 | |||
| d0b1607ff4 | |||
| 92546a28c0 | |||
| ce26fb5d1a | |||
| 38a57adf55 | |||
| e1d9590905 | |||
| 00a01e1a8e | |||
| 56e011bc7a | |||
| 5c6a03b10d | |||
| cc446433f6 | |||
| 2d0664a7c7 | |||
| 2192eea09f | |||
| 8659708e1a | |||
| dce54ceb67 | |||
| cab33d4842 | |||
| f318f614af | |||
| 581696ffab | |||
| 53cee7ecdd | |||
| 757f362918 | |||
| a8e73af806 | |||
| 61789d9238 | |||
| dd2082f40e | |||
| 755d6a9903 | |||
| c486131905 | |||
| 9ba2041f7b | |||
| 92ad7340fe | |||
| 6b2f8de210 | |||
| 69f3569ccf | |||
| 9937c1b484 | |||
| 43e497cf97 | |||
| 207c979f71 | |||
| 30bfd9eff8 | |||
| 3f8b5bf206 | |||
| d92b5a7623 | |||
| e4670491c7 | |||
| 1b94b2ca13 | |||
| 46dcb84985 | |||
| f7983b109f | |||
| 8ff9ed216c | |||
| f80d146012 | |||
| 1cb2cf3d54 | |||
| 97250d10b7 | |||
| 15979874ce |
2
.vscode/launch.json
vendored
2
.vscode/launch.json
vendored
@@ -7,7 +7,7 @@
|
|||||||
"type": "chrome",
|
"type": "chrome",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"preLaunchTask": "npm: start",
|
"preLaunchTask": "npm: start",
|
||||||
"url": "http://localhost:4200/"
|
"url": "http://localhost:4300/"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "ng test",
|
"name": "ng test",
|
||||||
|
|||||||
21
angular.json
21
angular.json
@@ -34,7 +34,12 @@
|
|||||||
"server": "src/main.server.ts",
|
"server": "src/main.server.ts",
|
||||||
"outputMode": "server",
|
"outputMode": "server",
|
||||||
"security": {
|
"security": {
|
||||||
"allowedHosts": ["localhost", "127.0.0.1"]
|
"allowedHosts": [
|
||||||
|
"localhost",
|
||||||
|
"localhost:4300",
|
||||||
|
"127.0.0.1",
|
||||||
|
"127.0.0.1:4300"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"ssr": {
|
"ssr": {
|
||||||
"entry": "src/server.ts"
|
"entry": "src/server.ts"
|
||||||
@@ -42,6 +47,9 @@
|
|||||||
},
|
},
|
||||||
"configurations": {
|
"configurations": {
|
||||||
"production": {
|
"production": {
|
||||||
|
"optimization": true,
|
||||||
|
"extractLicenses": true,
|
||||||
|
"sourceMap": false,
|
||||||
"budgets": [
|
"budgets": [
|
||||||
{
|
{
|
||||||
"type": "initial",
|
"type": "initial",
|
||||||
@@ -54,7 +62,13 @@
|
|||||||
"maximumError": "8kB"
|
"maximumError": "8kB"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"outputHashing": "all"
|
"outputHashing": "all",
|
||||||
|
"fileReplacements": [
|
||||||
|
{
|
||||||
|
"replace": "src/environments/environment.ts",
|
||||||
|
"with": "src/environments/environment.production.ts"
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"development": {
|
"development": {
|
||||||
"optimization": true,
|
"optimization": true,
|
||||||
@@ -73,6 +87,9 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"homo": {
|
"homo": {
|
||||||
|
"optimization": true,
|
||||||
|
"extractLicenses": true,
|
||||||
|
"sourceMap": false,
|
||||||
"fileReplacements": [
|
"fileReplacements": [
|
||||||
{
|
{
|
||||||
"replace": "src/environments/environment.ts",
|
"replace": "src/environments/environment.ts",
|
||||||
|
|||||||
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,7 +4,7 @@ import {
|
|||||||
provideAppInitializer,
|
provideAppInitializer,
|
||||||
provideBrowserGlobalErrorListeners,
|
provideBrowserGlobalErrorListeners,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { provideRouter } from '@angular/router';
|
import { provideRouter, UrlSerializer } from '@angular/router';
|
||||||
import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
|
import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
|
||||||
|
|
||||||
import { routes } from './app.routes';
|
import { routes } from './app.routes';
|
||||||
@@ -12,11 +12,14 @@ import { authBootstrap } from './core/services/auth/auth-bootstrap';
|
|||||||
import { authInterceptor } from './core/services/auth/auth.interceptor';
|
import { authInterceptor } from './core/services/auth/auth.interceptor';
|
||||||
import { globalLoadingInterceptor } from './core/services/global-loading/global-loading.interceptor';
|
import { globalLoadingInterceptor } from './core/services/global-loading/global-loading.interceptor';
|
||||||
import { tenantBootstrap } from './core/services/tenant-bootstrap';
|
import { tenantBootstrap } from './core/services/tenant-bootstrap';
|
||||||
|
import { TenantUrlSerializer } from './core/services/tenant-url.serializer';
|
||||||
|
|
||||||
function isStoreCatalogRequest(request: HttpRequest<unknown>): boolean {
|
export function isStoreCatalogRequest(request: HttpRequest<unknown>): boolean {
|
||||||
return (
|
return (
|
||||||
request.method === 'GET' &&
|
request.method === 'GET' &&
|
||||||
/\/api\/tenants\/[^/]+\/productos(?:\/\d+)?(?:\?|$)/.test(request.urlWithParams)
|
/\/api\/tenants\/[^/?#]+\/(?:catalog(?:\/featured-groups\/\d+\/items)?|catalog-items(?:\/\d+)?)\/?(?:[?#]|$)/.test(
|
||||||
|
request.urlWithParams,
|
||||||
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,6 +27,7 @@ export const appConfig: ApplicationConfig = {
|
|||||||
providers: [
|
providers: [
|
||||||
provideBrowserGlobalErrorListeners(),
|
provideBrowserGlobalErrorListeners(),
|
||||||
provideRouter(routes),
|
provideRouter(routes),
|
||||||
|
{ provide: UrlSerializer, useClass: TenantUrlSerializer },
|
||||||
provideClientHydration(
|
provideClientHydration(
|
||||||
withHttpTransferCacheOptions({
|
withHttpTransferCacheOptions({
|
||||||
includeRequestsWithAuthHeaders: true,
|
includeRequestsWithAuthHeaders: true,
|
||||||
|
|||||||
@@ -233,6 +233,19 @@ describe('app routes', () => {
|
|||||||
expect(compiled.textContent).toContain('No encontramos una tienda para este dominio');
|
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 () => {
|
it('redirects unauthenticated users from /checkout to /login', async () => {
|
||||||
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false));
|
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false));
|
||||||
|
|
||||||
|
|||||||
@@ -14,5 +14,12 @@ export const routes: Routes = [
|
|||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
loadChildren: () => import('./features/store/store.routes').then((m) => m.routes)
|
loadChildren: () => import('./features/store/store.routes').then((m) => m.routes)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '**',
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./shared/pages/route-not-found-page.component').then(
|
||||||
|
(m) => m.RouteNotFoundPageComponent,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|||||||
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';
|
import { TenantService } from '../services/tenant.service';
|
||||||
|
|
||||||
export const hasMenuGuard = (menuCode: string): CanActivateFn => {
|
export const hasMenuGuard = (menuCode: string): CanActivateFn => {
|
||||||
return () => {
|
return (_route, state) => {
|
||||||
const tenantService = inject(TenantService);
|
const tenantService = inject(TenantService);
|
||||||
const router = inject(Router);
|
const router = inject(Router);
|
||||||
|
|
||||||
const tenant = tenantService.tenant();
|
const tenant = tenantService.tenant();
|
||||||
|
|
||||||
if (!tenant) {
|
if (!tenant) {
|
||||||
return router.createUrlTree(['/']);
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasMenu = findMenu(tenant.menues ?? [], menuCode) !== undefined;
|
const hasMenu = findMenu(tenant.menues ?? [], menuCode) !== undefined;
|
||||||
|
|
||||||
if (hasMenu) {
|
if (hasMenu || state.url === '/') {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,14 +22,18 @@
|
|||||||
|
|
||||||
<div class="col-12 col-md-6 col-xl-5 d-grid gap-3 align-content-start store-layout__contact">
|
<div class="col-12 col-md-6 col-xl-5 d-grid gap-3 align-content-start store-layout__contact">
|
||||||
<div class="d-grid gap-2 store-layout__contact-details">
|
<div class="d-grid gap-2 store-layout__contact-details">
|
||||||
<div class="d-flex align-items-center gap-2">
|
@if (address) {
|
||||||
<i class="fa-solid fa-location-dot" aria-hidden="true"></i>
|
<div class="d-flex align-items-center gap-2">
|
||||||
<span>Av. San Lorenzo 1542, Rosario</span>
|
<i class="fa-solid fa-location-dot" aria-hidden="true"></i>
|
||||||
</div>
|
<span>{{ address }}</span>
|
||||||
<div class="d-flex align-items-center gap-2">
|
</div>
|
||||||
<i class="fa-solid fa-phone" aria-hidden="true"></i>
|
}
|
||||||
<span>54 9 (0341) 6658247</span>
|
@if (phone) {
|
||||||
</div>
|
<div class="d-flex align-items-center gap-2">
|
||||||
|
<i class="fa-solid fa-phone" aria-hidden="true"></i>
|
||||||
|
<span>{{ phone }}</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p class="mb-0 small store-layout__muted-text store-layout__copyright">
|
<p class="mb-0 small store-layout__muted-text store-layout__copyright">
|
||||||
|
|||||||
@@ -27,5 +27,7 @@ export class StoreFooterComponent {
|
|||||||
@Input() logoUrl: string | null = null;
|
@Input() logoUrl: string | null = null;
|
||||||
@Input() backgroundImageUrl: string | null = null;
|
@Input() backgroundImageUrl: string | null = null;
|
||||||
@Input() storeName: string | null = null;
|
@Input() storeName: string | null = null;
|
||||||
|
@Input() address: string | null = null;
|
||||||
|
@Input() phone: string | null = null;
|
||||||
readonly logoutClick = output<void>();
|
readonly logoutClick = output<void>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,11 @@
|
|||||||
[subtotal]="cartSubtotal()"
|
[subtotal]="cartSubtotal()"
|
||||||
[discount]="cartDiscount()"
|
[discount]="cartDiscount()"
|
||||||
[total]="cartTotal()"
|
[total]="cartTotal()"
|
||||||
|
[readonly]="!canModifyCart()"
|
||||||
|
[allowModify]="canModifyCart()"
|
||||||
|
[allowUpdateQuantity]="canUpdateCartQuantity()"
|
||||||
|
[allowUpdateVariant]="canUpdateCartVariant()"
|
||||||
|
[allowDelete]="canDeleteCartItems()"
|
||||||
[backgroundColor]="'#ffffff'"
|
[backgroundColor]="'#ffffff'"
|
||||||
(closed)="isCartOpen.set(false)"
|
(closed)="isCartOpen.set(false)"
|
||||||
>
|
>
|
||||||
@@ -62,6 +67,8 @@
|
|||||||
[logoUrl]="tenant()?.footer_logo ?? null"
|
[logoUrl]="tenant()?.footer_logo ?? null"
|
||||||
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
|
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
|
||||||
[storeName]="tenant()?.nombre ?? null"
|
[storeName]="tenant()?.nombre ?? null"
|
||||||
|
[address]="tenant()?.address ?? null"
|
||||||
|
[phone]="tenant()?.phone ?? null"
|
||||||
(logoutClick)="onLogoutClick()"
|
(logoutClick)="onLogoutClick()"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -21,6 +21,8 @@
|
|||||||
|
|
||||||
.store-layout__cart-dropdown {
|
.store-layout__cart-dropdown {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
top: 100px;
|
top: 100px;
|
||||||
right: calc((100% - 1320px) / 2 + 1.5rem);
|
right: calc((100% - 1320px) / 2 + 1.5rem);
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@@ -34,6 +36,10 @@
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
animation: store-layout-slide-down 0.2s ease-out;
|
animation: store-layout-slide-down 0.2s ease-out;
|
||||||
|
|
||||||
|
> app-cart {
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 1400px) {
|
@media (max-width: 1400px) {
|
||||||
right: 1.5rem;
|
right: 1.5rem;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,15 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { provideRouter, Router } from '@angular/router';
|
import {
|
||||||
|
ActivatedRoute,
|
||||||
|
convertToParamMap,
|
||||||
|
ParamMap,
|
||||||
|
provideRouter,
|
||||||
|
Router,
|
||||||
|
} from '@angular/router';
|
||||||
|
|
||||||
import { of } from 'rxjs';
|
import { BehaviorSubject, of } from 'rxjs';
|
||||||
|
|
||||||
import { Tenant } from '../../services/tenant.interface';
|
import { Tenant } from '../../services/tenant.interface';
|
||||||
import { TenantService } from '../../services/tenant.service';
|
import { TenantService } from '../../services/tenant.service';
|
||||||
@@ -22,6 +28,8 @@ const tenant: Tenant = {
|
|||||||
codigo: 'test',
|
codigo: 'test',
|
||||||
nombre: 'Test Tenant',
|
nombre: 'Test Tenant',
|
||||||
dominio: 'localhost',
|
dominio: 'localhost',
|
||||||
|
address: 'Calle Test 123, Rosario',
|
||||||
|
phone: '+54 341 555 1234',
|
||||||
primary_color: '#6376F3',
|
primary_color: '#6376F3',
|
||||||
secondary_color: '#A0A0A0',
|
secondary_color: '#A0A0A0',
|
||||||
danger_color: '#FF8888',
|
danger_color: '#FF8888',
|
||||||
@@ -32,6 +40,13 @@ const tenant: Tenant = {
|
|||||||
footer_logo: 'https://example.com/footer.png',
|
footer_logo: 'https://example.com/footer.png',
|
||||||
header_bg_image: 'https://example.com/header-background.png',
|
header_bg_image: 'https://example.com/header-background.png',
|
||||||
footer_bg_image: 'https://example.com/footer-background.png',
|
footer_bg_image: 'https://example.com/footer-background.png',
|
||||||
|
cart_editing_policy: {
|
||||||
|
code: 'full',
|
||||||
|
allow_modify: true,
|
||||||
|
allow_delete: true,
|
||||||
|
allow_update_quantity: true,
|
||||||
|
allow_update_variant: true,
|
||||||
|
},
|
||||||
categories: [],
|
categories: [],
|
||||||
menues: [
|
menues: [
|
||||||
{
|
{
|
||||||
@@ -133,11 +148,13 @@ describe('StoreLayoutComponent', () => {
|
|||||||
let cartState = signal<Cart | null>(null);
|
let cartState = signal<Cart | null>(null);
|
||||||
let authUserState = signal<AuthUser | null>(null);
|
let authUserState = signal<AuthUser | null>(null);
|
||||||
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
||||||
|
let queryParamMapState: BehaviorSubject<ParamMap>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
tenantState = signal<Tenant | null>(tenant);
|
tenantState = signal<Tenant | null>(tenant);
|
||||||
cartState = signal<Cart | null>(null);
|
cartState = signal<Cart | null>(null);
|
||||||
authUserState = signal<AuthUser | null>(null);
|
authUserState = signal<AuthUser | null>(null);
|
||||||
|
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
||||||
const isAuthenticatedState = signal(false);
|
const isAuthenticatedState = signal(false);
|
||||||
checkoutServiceStub = {
|
checkoutServiceStub = {
|
||||||
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
|
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
|
||||||
@@ -147,6 +164,10 @@ describe('StoreLayoutComponent', () => {
|
|||||||
imports: [StoreLayoutComponent],
|
imports: [StoreLayoutComponent],
|
||||||
providers: [
|
providers: [
|
||||||
provideRouter([]),
|
provideRouter([]),
|
||||||
|
{
|
||||||
|
provide: ActivatedRoute,
|
||||||
|
useValue: { queryParamMap: queryParamMapState.asObservable() },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
provide: TenantService,
|
provide: TenantService,
|
||||||
useValue: {
|
useValue: {
|
||||||
@@ -206,6 +227,19 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull();
|
expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('opens the cart when requested through the openCart query parameter', () => {
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
||||||
|
|
||||||
|
queryParamMapState.next(convertToParamMap({ openCart: 'true' }));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(true);
|
||||||
|
expect((fixture.nativeElement as HTMLElement).querySelector('app-cart')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it('hides the configured header elements when the tenant disables them', () => {
|
it('hides the configured header elements when the tenant disables them', () => {
|
||||||
tenantState.set({
|
tenantState.set({
|
||||||
...tenant,
|
...tenant,
|
||||||
@@ -267,6 +301,12 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(compiled.querySelector('.fa-whatsapp')).not.toBeNull();
|
expect(compiled.querySelector('.fa-whatsapp')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-facebook')).not.toBeNull();
|
expect(compiled.querySelector('.fa-facebook')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull();
|
expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull();
|
||||||
|
expect(compiled.querySelector('.store-layout__contact-details')?.textContent).toContain(
|
||||||
|
tenant.address,
|
||||||
|
);
|
||||||
|
expect(compiled.querySelector('.store-layout__contact-details')?.textContent).toContain(
|
||||||
|
tenant.phone,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('navigates to search results when the search button is clicked', () => {
|
it('navigates to search results when the search button is clicked', () => {
|
||||||
@@ -571,10 +611,9 @@ describe('StoreLayoutComponent', () => {
|
|||||||
precio_unitario: '100.00',
|
precio_unitario: '100.00',
|
||||||
catalog_item_id: 1,
|
catalog_item_id: 1,
|
||||||
variant_id: null,
|
variant_id: null,
|
||||||
product: {
|
nombre: 'Producto',
|
||||||
nombre: 'Producto',
|
imagen: null,
|
||||||
imagen: null,
|
variant: null,
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
@@ -624,10 +663,9 @@ describe('StoreLayoutComponent', () => {
|
|||||||
precio_unitario: '100.00',
|
precio_unitario: '100.00',
|
||||||
catalog_item_id: 1,
|
catalog_item_id: 1,
|
||||||
variant_id: null,
|
variant_id: null,
|
||||||
product: {
|
nombre: 'Producto',
|
||||||
nombre: 'Producto',
|
imagen: null,
|
||||||
imagen: null,
|
variant: null,
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
@@ -647,4 +685,102 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(cartItem.componentInstance.quantityDisabled()).toBe(false);
|
expect(cartItem.componentInstance.quantityDisabled()).toBe(false);
|
||||||
expect(buyButton).toBeDefined();
|
expect(buyButton).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('hides quantity selectors when the tenant disables cart editing', () => {
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
cart_editing_policy: {
|
||||||
|
code: 'disabled',
|
||||||
|
allow_modify: false,
|
||||||
|
allow_delete: false,
|
||||||
|
allow_update_quantity: false,
|
||||||
|
allow_update_variant: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
cartState.set({
|
||||||
|
id: 1,
|
||||||
|
tenant_codigo: tenant.codigo,
|
||||||
|
status: 'active',
|
||||||
|
subtotal: '100.00',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
cantidad: 1,
|
||||||
|
precio_unitario: '100.00',
|
||||||
|
catalog_item_id: 1,
|
||||||
|
variant_id: null,
|
||||||
|
nombre: 'Producto',
|
||||||
|
imagen: null,
|
||||||
|
variant: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
(fixture.componentInstance as any).isCartOpen.set(true);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const cartItem = fixture.debugElement.query(By.css('app-cart-item'));
|
||||||
|
expect(cartItem.componentInstance.readonly()).toBe(true);
|
||||||
|
expect(cartItem.nativeElement.querySelector('app-quantity-selector')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows variant selectors only for the full cart editing policy', () => {
|
||||||
|
const variantCart: Cart = {
|
||||||
|
id: 1,
|
||||||
|
tenant_codigo: tenant.codigo,
|
||||||
|
status: 'active',
|
||||||
|
subtotal: '100.00',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
cantidad: 1,
|
||||||
|
precio_unitario: '100.00',
|
||||||
|
catalog_item_id: 1,
|
||||||
|
variant_id: 10,
|
||||||
|
nombre: 'Producto',
|
||||||
|
imagen: null,
|
||||||
|
variant: { id: 10, precio: '100.00', stock_tecnico: 5, values: { talle: 'M' } },
|
||||||
|
variants: [
|
||||||
|
{ id: 10, precio: '100.00', stock_tecnico: 5, values: { talle: 'M' } },
|
||||||
|
{ id: 11, precio: '100.00', stock_tecnico: 5, values: { talle: 'L' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
cart_editing_policy: {
|
||||||
|
code: 'quantity_and_remove',
|
||||||
|
allow_modify: true,
|
||||||
|
allow_delete: true,
|
||||||
|
allow_update_quantity: true,
|
||||||
|
allow_update_variant: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
cartState.set(variantCart);
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
(fixture.componentInstance as any).isCartOpen.set(true);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelector('app-variant-selector')).toBeNull();
|
||||||
|
expect(fixture.nativeElement.querySelector('app-quantity-selector')).not.toBeNull();
|
||||||
|
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
cart_editing_policy: {
|
||||||
|
code: 'full',
|
||||||
|
allow_modify: true,
|
||||||
|
allow_delete: true,
|
||||||
|
allow_update_quantity: true,
|
||||||
|
allow_update_variant: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelector('app-variant-selector')).not.toBeNull();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Component, computed, inject, OnInit, signal } from '@angular/core';
|
import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
|
||||||
import { Router, RouterOutlet } from '@angular/router';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
|
import { ActivatedRoute, Router, RouterOutlet } from '@angular/router';
|
||||||
import { TenantService } from '../../services/tenant.service';
|
import { TenantService } from '../../services/tenant.service';
|
||||||
import { CartService } from '../../services/cart/cart.service';
|
import { CartService } from '../../services/cart/cart.service';
|
||||||
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
|
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
|
||||||
@@ -32,10 +33,25 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
private readonly toastService = inject(ToastService);
|
private readonly toastService = inject(ToastService);
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
protected readonly isCartOpen = signal(false);
|
protected readonly isCartOpen = signal(false);
|
||||||
protected readonly isCreatingPurchase = signal(false);
|
protected readonly isCreatingPurchase = signal(false);
|
||||||
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
|
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
|
||||||
|
protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
|
||||||
|
protected readonly canModifyCart = computed(
|
||||||
|
() => this.cartEditingPolicy()?.allow_modify ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canDeleteCartItems = computed(
|
||||||
|
() => this.cartEditingPolicy()?.allow_delete ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canUpdateCartQuantity = computed(
|
||||||
|
() => this.cartEditingPolicy()?.allow_update_quantity ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canUpdateCartVariant = computed(
|
||||||
|
() => this.cartEditingPolicy()?.allow_update_variant ?? false,
|
||||||
|
);
|
||||||
|
|
||||||
protected readonly cartSubtotal = computed(() => {
|
protected readonly cartSubtotal = computed(() => {
|
||||||
const cart = this.cartService.cart();
|
const cart = this.cartService.cart();
|
||||||
@@ -53,7 +69,7 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
private mapCartItemToMock(item: CartItem): CartItemMock {
|
private mapCartItemToMock(item: CartItem): CartItemMock {
|
||||||
const fullName = item.product?.nombre ?? '';
|
const fullName = item.nombre ?? '';
|
||||||
let product = fullName;
|
let product = fullName;
|
||||||
let attributes: { label: string; value: string }[] = [];
|
let attributes: { label: string; value: string }[] = [];
|
||||||
|
|
||||||
@@ -70,10 +86,7 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const variants = item.product?.variants ?? [];
|
const selectedVariant = item.variant;
|
||||||
const selectedVariant = item.product?.variants?.find(
|
|
||||||
(variant) => variant.id === item.variant_id,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (selectedVariant) {
|
if (selectedVariant) {
|
||||||
attributes = Object.entries(selectedVariant.values).map(([label, value]) => ({
|
attributes = Object.entries(selectedVariant.values).map(([label, value]) => ({
|
||||||
@@ -84,7 +97,7 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
cartItemId: item.id,
|
cartItemId: item.id,
|
||||||
imageUrl: item.product?.imagen ?? null,
|
imageUrl: item.imagen,
|
||||||
product,
|
product,
|
||||||
originalPrice: null,
|
originalPrice: null,
|
||||||
discountedPrice: parseFloat(item.precio_unitario),
|
discountedPrice: parseFloat(item.precio_unitario),
|
||||||
@@ -92,7 +105,7 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
attributes,
|
attributes,
|
||||||
quantity: item.cantidad,
|
quantity: item.cantidad,
|
||||||
variantId: item.variant_id,
|
variantId: item.variant_id,
|
||||||
variants,
|
variants: item.variants,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,6 +149,12 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
|
this.route.queryParamMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
|
||||||
|
if (params.get('openCart') === 'true') {
|
||||||
|
this.isCartOpen.set(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
this.cartService.loadCart().subscribe({
|
this.cartService.loadCart().subscribe({
|
||||||
error: (err) => console.error('Error loading cart', err),
|
error: (err) => console.error('Error loading cart', err),
|
||||||
});
|
});
|
||||||
@@ -168,8 +187,8 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
protected async onLogoutClick(): Promise<void> {
|
protected async onLogoutClick(): Promise<void> {
|
||||||
const isLeavingCheckout = this.router.url.startsWith('/checkout');
|
const isLeavingCheckout = this.router.url.startsWith('/checkout');
|
||||||
|
|
||||||
// Checkout must be left while the authenticated session is still valid so
|
// Leave checkout before closing the authenticated session so its component
|
||||||
// its CanDeactivate guard can cancel the pending purchase.
|
// can stop payment polling cleanly. The checkout itself remains pending.
|
||||||
if (isLeavingCheckout) {
|
if (isLeavingCheckout) {
|
||||||
const navigationSucceeded = await this.router.navigate(['/']);
|
const navigationSucceeded = await this.router.navigate(['/']);
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ import { PLATFORM_ID, TransferState } from '@angular/core';
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { TimeoutError } from 'rxjs';
|
||||||
|
|
||||||
import { environment } from '../../../../environments/environment';
|
import { environment } from '../../../../environments/environment';
|
||||||
|
import { BOOTSTRAP_REQUEST_TIMEOUT_MS } from '../bootstrap-request-timeout';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { CookieService } from '../cookie/cookie.service';
|
import { CookieService } from '../cookie/cookie.service';
|
||||||
import { TenantService } from '../tenant.service';
|
import { TenantService } from '../tenant.service';
|
||||||
@@ -181,6 +183,43 @@ describe('AuthService', () => {
|
|||||||
httpController.verify();
|
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', () => {
|
it('registers without creating a session', () => {
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { DOCUMENT } from '@angular/common';
|
|||||||
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
|
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
|
||||||
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
|
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
|
||||||
import { computed, inject, Injectable, PLATFORM_ID, signal, TransferState, makeStateKey } from '@angular/core';
|
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 { environment } from '../../../../environments/environment';
|
||||||
import { BaseApiService } from '../base-api.service';
|
import { BaseApiService } from '../base-api.service';
|
||||||
@@ -20,6 +20,7 @@ import {
|
|||||||
} from './auth.interfaces';
|
} from './auth.interfaces';
|
||||||
import { CookieService } from '../cookie/cookie.service';
|
import { CookieService } from '../cookie/cookie.service';
|
||||||
import { TenantService } from '../tenant.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_TOKEN_COOKIE_KEY = 'shopit.front.auth.token';
|
||||||
const AUTH_USER_SSR_STATE_KEY = makeStateKey<AuthUser>('shopit.auth.user');
|
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 cookieService = inject(CookieService);
|
||||||
private readonly transferState = inject(TransferState);
|
private readonly transferState = inject(TransferState);
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
|
private readonly bootstrapRequestTimeoutMs = inject(BOOTSTRAP_REQUEST_TIMEOUT_MS);
|
||||||
|
|
||||||
private readonly userState = signal<AuthUser | null>(null);
|
private readonly userState = signal<AuthUser | null>(null);
|
||||||
private readonly tokenState = signal<string | null>(null);
|
private readonly tokenState = signal<string | null>(null);
|
||||||
@@ -117,8 +119,12 @@ export class AuthService extends BaseApiService {
|
|||||||
|
|
||||||
const apiUrl = new URL(environment.url);
|
const apiUrl = new URL(environment.url);
|
||||||
const authorizationUrl = new URL('/auth/google/redirect', apiUrl.origin);
|
const authorizationUrl = new URL('/auth/google/redirect', apiUrl.origin);
|
||||||
|
const basePath = tenant.base_path && tenant.base_path !== '/' ? tenant.base_path : '';
|
||||||
authorizationUrl.searchParams.set('tenant', tenant.codigo);
|
authorizationUrl.searchParams.set('tenant', tenant.codigo);
|
||||||
authorizationUrl.searchParams.set('return_url', this.document.location.origin);
|
authorizationUrl.searchParams.set(
|
||||||
|
'return_url',
|
||||||
|
`${this.document.location.origin}${basePath}`,
|
||||||
|
);
|
||||||
|
|
||||||
this.document.location.assign(authorizationUrl.toString());
|
this.document.location.assign(authorizationUrl.toString());
|
||||||
}
|
}
|
||||||
@@ -175,7 +181,9 @@ export class AuthService extends BaseApiService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const user = await firstValueFrom(this.loadCurrentUser());
|
const user = await firstValueFrom(
|
||||||
|
this.loadCurrentUser().pipe(timeout(this.bootstrapRequestTimeoutMs)),
|
||||||
|
);
|
||||||
|
|
||||||
if (isPlatformServer(this.platformId)) {
|
if (isPlatformServer(this.platformId)) {
|
||||||
this.transferState.set(AUTH_USER_SSR_STATE_KEY, user);
|
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,9 +1,3 @@
|
|||||||
export interface CartItemProduct {
|
|
||||||
nombre: string;
|
|
||||||
imagen: string | null;
|
|
||||||
variants?: CartItemVariant[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CartItemVariantOption {
|
export interface CartItemVariantOption {
|
||||||
value: string;
|
value: string;
|
||||||
label: string;
|
label: string;
|
||||||
@@ -27,7 +21,10 @@ export interface CartItem {
|
|||||||
precio_unitario: string;
|
precio_unitario: string;
|
||||||
catalog_item_id: number;
|
catalog_item_id: number;
|
||||||
variant_id: number | null;
|
variant_id: number | null;
|
||||||
product: CartItemProduct | null;
|
nombre: string | null;
|
||||||
|
imagen: string | null;
|
||||||
|
variant: CartItemVariant | null;
|
||||||
|
variants?: CartItemVariant[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Cart {
|
export interface Cart {
|
||||||
|
|||||||
@@ -24,9 +24,13 @@ describe('CartService', () => {
|
|||||||
precio_unitario: '10.00',
|
precio_unitario: '10.00',
|
||||||
catalog_item_id: 5,
|
catalog_item_id: 5,
|
||||||
variant_id: 10,
|
variant_id: 10,
|
||||||
product: {
|
nombre: 'Test Product (Size: M)',
|
||||||
nombre: 'Test Product (Size: M)',
|
imagen: null,
|
||||||
imagen: null,
|
variant: {
|
||||||
|
id: 10,
|
||||||
|
precio: '10.00',
|
||||||
|
stock_tecnico: 1,
|
||||||
|
values: { size: 'M' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ export interface CatalogItemVariant {
|
|||||||
event_date_id?: number | null;
|
event_date_id?: number | null;
|
||||||
event_date_ids?: number[];
|
event_date_ids?: number[];
|
||||||
event_dates?: string[];
|
event_dates?: string[];
|
||||||
stock_tecnico: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
minimum_use_date?: string | null;
|
minimum_use_date?: string | null;
|
||||||
maximum_use_date?: string | null;
|
maximum_use_date?: string | null;
|
||||||
effective_minimum_use_date?: string | null;
|
effective_minimum_use_date?: string | null;
|
||||||
@@ -98,7 +98,7 @@ export interface CatalogItemDetail {
|
|||||||
attributes: ProductAttribute[];
|
attributes: ProductAttribute[];
|
||||||
variants: CatalogItemVariant[];
|
variants: CatalogItemVariant[];
|
||||||
selected_variant?: SelectedCatalogItemVariant;
|
selected_variant?: SelectedCatalogItemVariant;
|
||||||
stock_tecnico?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
images?: string[];
|
images?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,10 +113,31 @@ export interface CatalogFeaturedItemVariant {
|
|||||||
id: number;
|
id: number;
|
||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string;
|
precio?: string;
|
||||||
stock_tecnico: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
values: Record<string, CatalogVariantValue>;
|
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 {
|
export interface CatalogFeaturedItem {
|
||||||
id: number;
|
id: number;
|
||||||
type: CatalogItemType;
|
type: CatalogItemType;
|
||||||
@@ -124,7 +145,7 @@ export interface CatalogFeaturedItem {
|
|||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio: number | string;
|
precio: number | string;
|
||||||
image?: string | null;
|
image?: string | null;
|
||||||
stock_tecnico?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
variants?: CatalogFeaturedItemVariant[];
|
variants?: CatalogFeaturedItemVariant[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +155,7 @@ export type CatalogFeaturedItems =
|
|||||||
|
|
||||||
export interface CatalogFeaturedGroup {
|
export interface CatalogFeaturedGroup {
|
||||||
id: number;
|
id: number;
|
||||||
|
code: string;
|
||||||
title: string;
|
title: string;
|
||||||
layout: CatalogProductLayout;
|
layout: CatalogProductLayout;
|
||||||
group_layout: CatalogGroupLayout;
|
group_layout: CatalogGroupLayout;
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
CatalogFeaturedItem,
|
CatalogFeaturedItem,
|
||||||
CatalogFeaturedItems,
|
CatalogFeaturedItems,
|
||||||
CatalogItemDetail,
|
CatalogItemDetail,
|
||||||
|
CatalogVariantOptionsResponse,
|
||||||
CategoryItemsResponse,
|
CategoryItemsResponse,
|
||||||
Product,
|
Product,
|
||||||
} from './catalog.interface';
|
} from './catalog.interface';
|
||||||
@@ -74,10 +75,7 @@ export class CatalogService extends BaseApiService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getCatalogItem(
|
getCatalogItem(id: number, variantId?: number): Observable<CatalogItemDetail> {
|
||||||
id: number,
|
|
||||||
variantId?: number,
|
|
||||||
): Observable<CatalogItemDetail> {
|
|
||||||
let params = new HttpParams();
|
let params = new HttpParams();
|
||||||
if (variantId) {
|
if (variantId) {
|
||||||
params = params.set('variant_id', variantId);
|
params = params.set('variant_id', variantId);
|
||||||
@@ -90,6 +88,20 @@ export class CatalogService extends BaseApiService {
|
|||||||
.pipe(map((response) => response.data));
|
.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 {
|
private buildHttpParams(params?: ApiPaginationQueryParams): HttpParams {
|
||||||
if (!params) {
|
if (!params) {
|
||||||
return new HttpParams();
|
return new HttpParams();
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { firstValueFrom } from 'rxjs';
|
|||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
import { BaseApiService } from './base-api.service';
|
import { BaseApiService } from './base-api.service';
|
||||||
|
import { CartItemVariant } from './cart/cart.interface';
|
||||||
|
|
||||||
export interface UpdatePurchaseCustomerPayload {
|
export interface UpdatePurchaseCustomerPayload {
|
||||||
dni: string;
|
dni: string;
|
||||||
@@ -73,6 +74,7 @@ export interface PurchaseDetailItemResponse {
|
|||||||
line_total: string;
|
line_total: string;
|
||||||
source_catalog_item_id: number | null;
|
source_catalog_item_id: number | null;
|
||||||
source_variant_id: number | null;
|
source_variant_id: number | null;
|
||||||
|
variants?: CartItemVariant[];
|
||||||
item_details: {
|
item_details: {
|
||||||
nombre: string;
|
nombre: string;
|
||||||
descripcion: string | null;
|
descripcion: string | null;
|
||||||
@@ -95,7 +97,7 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
|||||||
telefono: string | null;
|
telefono: string | null;
|
||||||
nombre_apellido: string | null;
|
nombre_apellido: string | null;
|
||||||
email: string | null;
|
email: string | null;
|
||||||
items_source: 'purchase';
|
items_source: 'purchase' | 'cart';
|
||||||
items: PurchaseDetailItemResponse[];
|
items: PurchaseDetailItemResponse[];
|
||||||
tickets_count?: number;
|
tickets_count?: number;
|
||||||
has_generated_tickets?: boolean;
|
has_generated_tickets?: boolean;
|
||||||
@@ -130,7 +132,7 @@ export class CheckoutService extends BaseApiService {
|
|||||||
async generatePaymentIntent(
|
async generatePaymentIntent(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
method: 'qr' | 'transfer' | 'telepagos',
|
method: 'qr' | 'transfer',
|
||||||
payerDni?: string,
|
payerDni?: string,
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
const payload: any = { method };
|
const payload: any = { method };
|
||||||
@@ -174,7 +176,20 @@ export class CheckoutService extends BaseApiService {
|
|||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
itemId: number,
|
itemId: number,
|
||||||
quantity: number,
|
quantity: number,
|
||||||
|
cartId: number | null = null,
|
||||||
|
itemsSource: 'purchase' | 'cart' = 'purchase',
|
||||||
): Promise<PurchaseDetailResponse> {
|
): Promise<PurchaseDetailResponse> {
|
||||||
|
if (itemsSource === 'cart' && cartId !== null) {
|
||||||
|
await firstValueFrom(
|
||||||
|
this.http.patch(
|
||||||
|
`${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`,
|
||||||
|
{ cantidad: quantity },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.getPurchase(tenantCode, purchaseId);
|
||||||
|
}
|
||||||
|
|
||||||
const response = await firstValueFrom(
|
const response = await firstValueFrom(
|
||||||
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
|
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
|
||||||
@@ -190,6 +205,51 @@ export class CheckoutService extends BaseApiService {
|
|||||||
return purchase;
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateItemVariant(
|
||||||
|
tenantCode: string,
|
||||||
|
purchaseId: number,
|
||||||
|
itemId: number,
|
||||||
|
variantId: number,
|
||||||
|
quantity: number,
|
||||||
|
cartId: number | null = null,
|
||||||
|
itemsSource: 'purchase' | 'cart' = 'purchase',
|
||||||
|
): Promise<PurchaseDetailResponse> {
|
||||||
|
if (itemsSource === 'cart' && cartId !== null) {
|
||||||
|
await firstValueFrom(
|
||||||
|
this.http.patch(
|
||||||
|
`${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`,
|
||||||
|
{ cantidad: quantity, variant_id: variantId },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await firstValueFrom(
|
||||||
|
this.http.patch(
|
||||||
|
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
|
||||||
|
{ quantity, variant_id: variantId },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.getPurchase(tenantCode, purchaseId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeItem(
|
||||||
|
tenantCode: string,
|
||||||
|
purchaseId: number,
|
||||||
|
itemId: number,
|
||||||
|
cartId: number | null = null,
|
||||||
|
itemsSource: 'purchase' | 'cart' = 'purchase',
|
||||||
|
): Promise<PurchaseDetailResponse> {
|
||||||
|
const url =
|
||||||
|
itemsSource === 'cart' && cartId !== null
|
||||||
|
? `${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`
|
||||||
|
: `${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`;
|
||||||
|
|
||||||
|
await firstValueFrom(this.http.delete(url));
|
||||||
|
|
||||||
|
return this.getPurchase(tenantCode, purchaseId);
|
||||||
|
}
|
||||||
|
|
||||||
async prepareItemEditing(
|
async prepareItemEditing(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
|
|||||||
50
src/app/core/services/tenant-url.serializer.spec.ts
Normal file
50
src/app/core/services/tenant-url.serializer.spec.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import '@angular/compiler';
|
||||||
|
import { DefaultUrlSerializer } from '@angular/router';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { Tenant } from './tenant.interface';
|
||||||
|
import { TenantService } from './tenant.service';
|
||||||
|
import { TenantUrlSerializer } from './tenant-url.serializer';
|
||||||
|
|
||||||
|
describe('TenantUrlSerializer', () => {
|
||||||
|
const defaultSerializer = new DefaultUrlSerializer();
|
||||||
|
|
||||||
|
function createSerializer(basePath: string): TenantUrlSerializer {
|
||||||
|
const tenantService = {
|
||||||
|
getTenant: () => ({ base_path: basePath }) as Tenant,
|
||||||
|
} as TenantService;
|
||||||
|
|
||||||
|
return new TenantUrlSerializer(tenantService);
|
||||||
|
}
|
||||||
|
|
||||||
|
it('keeps root tenants unchanged', () => {
|
||||||
|
const serializer = createSerializer('/');
|
||||||
|
const tree = serializer.parse('/producto/123?ref=home');
|
||||||
|
|
||||||
|
expect(defaultSerializer.serialize(tree)).toBe('/producto/123?ref=home');
|
||||||
|
expect(serializer.serialize(tree)).toBe('/producto/123?ref=home');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes the tenant base path when parsing and restores it when serializing', () => {
|
||||||
|
const serializer = createSerializer('/desfile');
|
||||||
|
const tree = serializer.parse('/desfile/producto/123?ref=home#detalle');
|
||||||
|
|
||||||
|
expect(defaultSerializer.serialize(tree)).toBe('/producto/123?ref=home#detalle');
|
||||||
|
expect(serializer.serialize(tree)).toBe('/desfile/producto/123?ref=home#detalle');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps the tenant base path to the application root', () => {
|
||||||
|
const serializer = createSerializer('/desfile/');
|
||||||
|
const tree = serializer.parse('/desfile');
|
||||||
|
|
||||||
|
expect(defaultSerializer.serialize(tree)).toBe('/');
|
||||||
|
expect(serializer.serialize(tree)).toBe('/desfile');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not strip partial path segment matches', () => {
|
||||||
|
const serializer = createSerializer('/desfile');
|
||||||
|
const tree = serializer.parse('/desfile-shop/producto/123');
|
||||||
|
|
||||||
|
expect(defaultSerializer.serialize(tree)).toBe('/desfile-shop/producto/123');
|
||||||
|
});
|
||||||
|
});
|
||||||
66
src/app/core/services/tenant-url.serializer.ts
Normal file
66
src/app/core/services/tenant-url.serializer.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import { Injectable } from '@angular/core';
|
||||||
|
import { DefaultUrlSerializer, UrlSerializer, UrlTree } from '@angular/router';
|
||||||
|
|
||||||
|
import { TenantService } from './tenant.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TenantUrlSerializer extends UrlSerializer {
|
||||||
|
private readonly defaultSerializer = new DefaultUrlSerializer();
|
||||||
|
|
||||||
|
constructor(private readonly tenantService: TenantService) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
override parse(url: string): UrlTree {
|
||||||
|
return this.defaultSerializer.parse(this.removeBasePath(url));
|
||||||
|
}
|
||||||
|
|
||||||
|
override serialize(tree: UrlTree): string {
|
||||||
|
const url = this.defaultSerializer.serialize(tree);
|
||||||
|
const basePath = this.basePath();
|
||||||
|
|
||||||
|
if (basePath === '/') {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
return url === '/' ? basePath : `${basePath}${url}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private removeBasePath(url: string): string {
|
||||||
|
const basePath = this.basePath();
|
||||||
|
|
||||||
|
if (basePath === '/' || !this.startsWithCompletePathSegment(url, basePath)) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
const remainder = url.slice(basePath.length);
|
||||||
|
|
||||||
|
if (remainder === '') {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
return remainder.startsWith('?') || remainder.startsWith('#')
|
||||||
|
? `/${remainder}`
|
||||||
|
: remainder;
|
||||||
|
}
|
||||||
|
|
||||||
|
private basePath(): string {
|
||||||
|
const configuredPath = this.tenantService.getTenant()?.base_path?.trim() ?? '/';
|
||||||
|
|
||||||
|
if (configuredPath === '' || configuredPath === '/') {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
return `/${configuredPath.replace(/^\/+|\/+$/g, '')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private startsWithCompletePathSegment(url: string, basePath: string): boolean {
|
||||||
|
if (!url.startsWith(basePath)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const boundary = url.charAt(basePath.length);
|
||||||
|
|
||||||
|
return boundary === '' || boundary === '/' || boundary === '?' || boundary === '#';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,15 @@
|
|||||||
import { ApiResponse } from './api-response.interface';
|
import { ApiResponse } from './api-response.interface';
|
||||||
|
|
||||||
|
export type CartEditingPolicyCode = 'disabled' | 'quantity_and_remove' | 'full';
|
||||||
|
|
||||||
|
export interface CartEditingPolicy {
|
||||||
|
code: CartEditingPolicyCode;
|
||||||
|
allow_modify: boolean;
|
||||||
|
allow_delete: boolean;
|
||||||
|
allow_update_quantity: boolean;
|
||||||
|
allow_update_variant: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface BankAccount {
|
export interface BankAccount {
|
||||||
id: number;
|
id: number;
|
||||||
tenant_code: string;
|
tenant_code: string;
|
||||||
@@ -20,13 +30,18 @@ export interface WebsiteType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface HeroConfig {
|
export interface HeroConfig {
|
||||||
background_image_id?: string | null;
|
background_image_id?: string | ResponsiveImage | null;
|
||||||
title_html?: string | null;
|
title_html?: string | null;
|
||||||
description_html?: string | null;
|
description_html?: string | null;
|
||||||
button_text?: string | null;
|
button_text?: string | null;
|
||||||
button_href?: string | null;
|
button_href?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ResponsiveImage {
|
||||||
|
desktop: string;
|
||||||
|
mobile: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AdditionalInfoConfig {
|
export interface AdditionalInfoConfig {
|
||||||
description?: string | null;
|
description?: string | null;
|
||||||
}
|
}
|
||||||
@@ -96,7 +111,10 @@ export interface Tenant {
|
|||||||
codigo: string;
|
codigo: string;
|
||||||
nombre: string;
|
nombre: string;
|
||||||
dominio: string;
|
dominio: string;
|
||||||
|
base_path?: string;
|
||||||
site_title?: string | null;
|
site_title?: string | null;
|
||||||
|
address?: string | null;
|
||||||
|
phone?: string | null;
|
||||||
favicon?: string | null;
|
favicon?: string | null;
|
||||||
primary_color: string;
|
primary_color: string;
|
||||||
secondary_color: string;
|
secondary_color: string;
|
||||||
@@ -121,6 +139,9 @@ export interface Tenant {
|
|||||||
display_categories?: boolean;
|
display_categories?: boolean;
|
||||||
display_seach_bar?: boolean;
|
display_seach_bar?: boolean;
|
||||||
display_cart?: boolean;
|
display_cart?: boolean;
|
||||||
|
cart_editing_policy?: CartEditingPolicy;
|
||||||
|
checkout_editing_policy?: CartEditingPolicy;
|
||||||
|
display_cart_item_images?: boolean;
|
||||||
social_media?: SocialMedia[];
|
social_media?: SocialMedia[];
|
||||||
menues?: Menu[];
|
menues?: Menu[];
|
||||||
categories: Category[];
|
categories: Category[];
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ import { PLATFORM_ID, REQUEST, RESPONSE_INIT, TransferState } from '@angular/cor
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { TimeoutError } from 'rxjs';
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { BOOTSTRAP_REQUEST_TIMEOUT_MS } from './bootstrap-request-timeout';
|
||||||
import { Tenant, TenantBootstrapResponse } from './tenant.interface';
|
import { Tenant, TenantBootstrapResponse } from './tenant.interface';
|
||||||
import { TENANT_SSR_STATE_KEY } from './tenant-ssr-cache.store';
|
import { TENANT_SSR_STATE_KEY } from './tenant-ssr-cache.store';
|
||||||
import { TenantService } from './tenant.service';
|
import { TenantService } from './tenant.service';
|
||||||
@@ -29,15 +31,15 @@ const tenant: Tenant = {
|
|||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
nombre: 'Manga corta',
|
nombre: 'Manga corta',
|
||||||
subcategories: []
|
subcategories: [],
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
const tenantResponse: TenantBootstrapResponse = {
|
const tenantResponse: TenantBootstrapResponse = {
|
||||||
data: tenant
|
data: tenant,
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('TenantService', () => {
|
describe('TenantService', () => {
|
||||||
@@ -51,14 +53,16 @@ describe('TenantService', () => {
|
|||||||
|
|
||||||
it('requests the tenant bootstrap endpoint using the current hostname and stores the response', async () => {
|
it('requests the tenant bootstrap endpoint using the current hostname and stores the response', async () => {
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService]
|
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService],
|
||||||
});
|
});
|
||||||
|
|
||||||
const service = TestBed.inject(TenantService);
|
const service = TestBed.inject(TenantService);
|
||||||
const httpController = TestBed.inject(HttpTestingController);
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
const bootstrapPromise = service.bootstrap();
|
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');
|
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 () => {
|
it('hydrates the tenant from TransferState without performing HTTP on the browser', async () => {
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService]
|
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService],
|
||||||
});
|
});
|
||||||
|
|
||||||
const service = TestBed.inject(TenantService);
|
const service = TestBed.inject(TenantService);
|
||||||
@@ -83,7 +87,7 @@ describe('TenantService', () => {
|
|||||||
|
|
||||||
transferState.set(TENANT_SSR_STATE_KEY, {
|
transferState.set(TENANT_SSR_STATE_KEY, {
|
||||||
status: 'ready',
|
status: 'ready',
|
||||||
tenant
|
tenant,
|
||||||
});
|
});
|
||||||
|
|
||||||
await expect(service.bootstrap()).resolves.toBeUndefined();
|
await expect(service.bootstrap()).resolves.toBeUndefined();
|
||||||
@@ -109,12 +113,12 @@ describe('TenantService', () => {
|
|||||||
useValue: new Request('https://internal.example/render', {
|
useValue: new Request('https://internal.example/render', {
|
||||||
headers: {
|
headers: {
|
||||||
'x-forwarded-host': 'STORE.EXAMPLE.COM:443, proxy.internal',
|
'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);
|
const service = TestBed.inject(TenantService);
|
||||||
@@ -122,7 +126,9 @@ describe('TenantService', () => {
|
|||||||
const httpController = TestBed.inject(HttpTestingController);
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
const bootstrapPromise = service.bootstrap();
|
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);
|
request.flush(tenantResponse);
|
||||||
|
|
||||||
@@ -131,7 +137,7 @@ describe('TenantService', () => {
|
|||||||
expect(service.tenant()).toEqual(tenant);
|
expect(service.tenant()).toEqual(tenant);
|
||||||
expect(transferState.get(TENANT_SSR_STATE_KEY, null)).toEqual({
|
expect(transferState.get(TENANT_SSR_STATE_KEY, null)).toEqual({
|
||||||
status: 'ready',
|
status: 'ready',
|
||||||
tenant
|
tenant,
|
||||||
});
|
});
|
||||||
expect(responseInit.status).toBeUndefined();
|
expect(responseInit.status).toBeUndefined();
|
||||||
|
|
||||||
@@ -151,12 +157,12 @@ describe('TenantService', () => {
|
|||||||
provide: REQUEST,
|
provide: REQUEST,
|
||||||
useValue: new Request('https://internal.example/render', {
|
useValue: new Request('https://internal.example/render', {
|
||||||
headers: {
|
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);
|
const service = TestBed.inject(TenantService);
|
||||||
@@ -164,7 +170,9 @@ describe('TenantService', () => {
|
|||||||
const httpController = TestBed.inject(HttpTestingController);
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
const bootstrapPromise = service.bootstrap();
|
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' });
|
request.flush({ message: 'Not Found' }, { status: 404, statusText: 'Not Found' });
|
||||||
|
|
||||||
@@ -173,7 +181,7 @@ describe('TenantService', () => {
|
|||||||
expect(service.tenant()).toBeNull();
|
expect(service.tenant()).toBeNull();
|
||||||
expect(service.getTenant()).toBeNull();
|
expect(service.getTenant()).toBeNull();
|
||||||
expect(transferState.get(TENANT_SSR_STATE_KEY, null)).toEqual({
|
expect(transferState.get(TENANT_SSR_STATE_KEY, null)).toEqual({
|
||||||
status: 'not-found'
|
status: 'not-found',
|
||||||
});
|
});
|
||||||
expect(responseInit.status).toBe(404);
|
expect(responseInit.status).toBe(404);
|
||||||
|
|
||||||
@@ -182,14 +190,16 @@ describe('TenantService', () => {
|
|||||||
|
|
||||||
it('rejects when the bootstrap response does not contain tenant data', async () => {
|
it('rejects when the bootstrap response does not contain tenant data', async () => {
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService]
|
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService],
|
||||||
});
|
});
|
||||||
|
|
||||||
const service = TestBed.inject(TenantService);
|
const service = TestBed.inject(TenantService);
|
||||||
const httpController = TestBed.inject(HttpTestingController);
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
const bootstrapPromise = service.bootstrap();
|
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({});
|
request.flush({});
|
||||||
|
|
||||||
@@ -213,19 +223,21 @@ describe('TenantService', () => {
|
|||||||
provide: REQUEST,
|
provide: REQUEST,
|
||||||
useValue: new Request('https://internal.example/render', {
|
useValue: new Request('https://internal.example/render', {
|
||||||
headers: {
|
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 service = TestBed.inject(TenantService);
|
||||||
const httpController = TestBed.inject(HttpTestingController);
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
const bootstrapPromise = service.bootstrap();
|
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' });
|
request.flush({ message: 'Boom' }, { status: 500, statusText: 'Server Error' });
|
||||||
|
|
||||||
@@ -235,4 +247,39 @@ describe('TenantService', () => {
|
|||||||
|
|
||||||
httpController.verify();
|
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,
|
REQUEST,
|
||||||
RESPONSE_INIT,
|
RESPONSE_INIT,
|
||||||
signal,
|
signal,
|
||||||
TransferState
|
TransferState,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { IS_DISCOVERING_ROUTES } from '@angular/ssr';
|
import { IS_DISCOVERING_ROUTES } from '@angular/ssr';
|
||||||
import { firstValueFrom } from 'rxjs';
|
import { firstValueFrom, timeout } from 'rxjs';
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
import { BaseApiService } from './base-api.service';
|
import { BaseApiService } from './base-api.service';
|
||||||
|
import { BOOTSTRAP_REQUEST_TIMEOUT_MS } from './bootstrap-request-timeout';
|
||||||
import { Tenant, TenantBootstrapResponse } from './tenant.interface';
|
import { Tenant, TenantBootstrapResponse } from './tenant.interface';
|
||||||
import {
|
import {
|
||||||
TENANT_SSR_STATE_KEY,
|
TENANT_SSR_STATE_KEY,
|
||||||
TenantBootstrapStatus,
|
TenantBootstrapStatus,
|
||||||
TenantSsrState
|
TenantSsrState,
|
||||||
} from './tenant-ssr-cache.store';
|
} from './tenant-ssr-cache.store';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root'
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class TenantService extends BaseApiService {
|
export class TenantService extends BaseApiService {
|
||||||
private readonly platformId = inject(PLATFORM_ID);
|
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 responseInit = inject(RESPONSE_INIT, { optional: true });
|
||||||
private readonly transferState = inject(TransferState);
|
private readonly transferState = inject(TransferState);
|
||||||
private readonly isDiscoveringRoutes = inject(IS_DISCOVERING_ROUTES, { optional: true }) ?? false;
|
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 tenantState = signal<Tenant | null>(null);
|
||||||
private readonly statusState = signal<TenantBootstrapStatus>('idle');
|
private readonly statusState = signal<TenantBootstrapStatus>('idle');
|
||||||
|
|
||||||
@@ -48,7 +50,6 @@ export class TenantService extends BaseApiService {
|
|||||||
return `${environment.url}tenants/${tenant.codigo}`;
|
return `${environment.url}tenants/${tenant.codigo}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async bootstrap(): Promise<void> {
|
async bootstrap(): Promise<void> {
|
||||||
if (this.statusState() !== 'idle') {
|
if (this.statusState() !== 'idle') {
|
||||||
return;
|
return;
|
||||||
@@ -69,13 +70,18 @@ export class TenantService extends BaseApiService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const domain = this.resolveDomain();
|
const { domain, path } = this.resolveRequestContext();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await firstValueFrom(
|
const response = await firstValueFrom(
|
||||||
this.http.get<TenantBootstrapResponse>(
|
this.http
|
||||||
`${environment.url}tenants/bootstrap/${domain}`
|
.get<TenantBootstrapResponse>(`${environment.url}tenants/bootstrap`, {
|
||||||
)
|
params: {
|
||||||
|
dominio: domain,
|
||||||
|
path,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.pipe(timeout(this.bootstrapRequestTimeoutMs)),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!response?.data) {
|
if (!response?.data) {
|
||||||
@@ -85,7 +91,7 @@ export class TenantService extends BaseApiService {
|
|||||||
this.setReady(response.data);
|
this.setReady(response.data);
|
||||||
this.persistSsrState({
|
this.persistSsrState({
|
||||||
status: 'ready',
|
status: 'ready',
|
||||||
tenant: response.data
|
tenant: response.data,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (this.isNotFoundError(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)) {
|
if (isPlatformBrowser(this.platformId)) {
|
||||||
const domain = window.location.hostname;
|
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.');
|
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 =
|
const requestHost =
|
||||||
@@ -123,7 +132,14 @@ export class TenantService extends BaseApiService {
|
|||||||
throw new Error('Tenant bootstrap could not resolve the current domain.');
|
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 {
|
private normalizeHost(host: string): string {
|
||||||
@@ -145,6 +161,16 @@ export class TenantService extends BaseApiService {
|
|||||||
return normalizedHost.replace(/:\d+$/, '');
|
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 {
|
private applyState(state: TenantSsrState): void {
|
||||||
if (state.status === 'ready') {
|
if (state.status === 'ready') {
|
||||||
this.setReady(state.tenant);
|
this.setReady(state.tenant);
|
||||||
|
|||||||
@@ -767,11 +767,11 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<app-product-ticket-selector
|
<app-product-ticket-selector
|
||||||
|
[productId]="1"
|
||||||
[title]="testTicketSelectorProduct.title"
|
[title]="testTicketSelectorProduct.title"
|
||||||
[description]="testTicketSelectorProduct.description"
|
[description]="testTicketSelectorProduct.description"
|
||||||
[price]="testTicketSelectorProduct.price"
|
[price]="testTicketSelectorProduct.price"
|
||||||
[imageUrl]="testTicketSelectorProduct.imageUrl"
|
[imageUrl]="testTicketSelectorProduct.imageUrl"
|
||||||
[variants]="testTicketSelectorProduct.variants"
|
|
||||||
(buy)="onTicketBuy($event)"
|
(buy)="onTicketBuy($event)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -232,7 +232,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1001,
|
id: 1001,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -243,7 +243,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1002,
|
id: 1002,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -254,7 +254,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1003,
|
id: 1003,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('c', 'Sector C'),
|
sector: ticketOption('c', 'Sector C'),
|
||||||
@@ -265,7 +265,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1004,
|
id: 1004,
|
||||||
precio: 200000,
|
precio: 200000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -276,7 +276,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1005,
|
id: 1005,
|
||||||
precio: 200000,
|
precio: 200000,
|
||||||
stock_tecnico: 0,
|
maximum_addable_quantity: 0,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -287,7 +287,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1006,
|
id: 1006,
|
||||||
precio: 100000,
|
precio: 100000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('b', 'Sector B'),
|
sector: ticketOption('b', 'Sector B'),
|
||||||
@@ -298,7 +298,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1007,
|
id: 1007,
|
||||||
precio: 100000,
|
precio: 100000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('b', 'Sector B'),
|
sector: ticketOption('b', 'Sector B'),
|
||||||
@@ -309,7 +309,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1008,
|
id: 1008,
|
||||||
precio: 90000,
|
precio: 90000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
@@ -320,7 +320,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1009,
|
id: 1009,
|
||||||
precio: 65000,
|
precio: 65000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
@@ -331,7 +331,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1010,
|
id: 1010,
|
||||||
precio: 40000,
|
precio: 40000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
stock_tecnico: null,
|
maximum_addable_quantity: null,
|
||||||
values: { size: 'S' },
|
values: { size: 'S' },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -51,12 +51,12 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
stock_tecnico: 0,
|
maximum_addable_quantity: 0,
|
||||||
values: { size: 'S' },
|
values: { size: 'S' },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
stock_tecnico: 2,
|
maximum_addable_quantity: 2,
|
||||||
values: { size: 'M' },
|
values: { size: 'M' },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -92,9 +92,9 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
]);
|
]);
|
||||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{ id: 1, stock_tecnico: null, values: { event_date: '1' } },
|
{ id: 1, maximum_addable_quantity: null, values: { event_date: '1' } },
|
||||||
{ id: 2, stock_tecnico: null, values: { event_date: '2' } },
|
{ id: 2, maximum_addable_quantity: null, values: { event_date: '2' } },
|
||||||
{ id: 3, stock_tecnico: null, values: { event_date: ['1', '2'] } },
|
{ id: 3, maximum_addable_quantity: null, values: { event_date: ['1', '2'] } },
|
||||||
]);
|
]);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
@@ -135,8 +135,8 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
]);
|
]);
|
||||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{ id: 1, stock_tecnico: null, values: { size: 'S', internal_type: 'adult' } },
|
{ id: 1, maximum_addable_quantity: null, values: { size: 'S', internal_type: 'adult' } },
|
||||||
{ id: 2, stock_tecnico: null, values: { size: 'M', internal_type: 'child' } },
|
{ id: 2, maximum_addable_quantity: null, values: { size: 'M', internal_type: 'child' } },
|
||||||
]);
|
]);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
|||||||
@@ -227,7 +227,7 @@ export class ProductAttributeSelectorComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
||||||
return this.inventoryPolicy() === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
|
return variant.maximum_addable_quantity !== 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
private findFirstHexValue(value: unknown): string | null {
|
private findFirstHexValue(value: unknown): string | null {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
[layout]="categoryResults.layout"
|
[layout]="categoryResults.layout"
|
||||||
[groupLayout]="paginatedLayout"
|
[groupLayout]="paginatedLayout"
|
||||||
[items]="categoryResults"
|
[items]="categoryResults"
|
||||||
|
[savingProductIds]="savingProductIds()"
|
||||||
(buy)="onBuyProduct($event)"
|
(buy)="onBuyProduct($event)"
|
||||||
(addToCart)="onAddToCart($event)"
|
(addToCart)="onAddToCart($event)"
|
||||||
(pageChange)="onPageChange($event)"
|
(pageChange)="onPageChange($event)"
|
||||||
|
|||||||
@@ -9,7 +9,16 @@ import {
|
|||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
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 { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.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 results = signal<CategoryItemsResponse | null>(null);
|
||||||
protected readonly error = signal<string | null>(null);
|
protected readonly error = signal<string | null>(null);
|
||||||
protected readonly creatingDirectPurchase = signal(false);
|
protected readonly creatingDirectPurchase = signal(false);
|
||||||
|
protected readonly savingProductIds = signal<ReadonlySet<number>>(new Set<number>());
|
||||||
protected readonly paginatedLayout: CatalogGroupLayout = 'paginated';
|
protected readonly paginatedLayout: CatalogGroupLayout = 'paginated';
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -113,7 +123,9 @@ export class CategoryItemsPageComponent {
|
|||||||
|
|
||||||
if (!this.injector.get(AuthService).user()) {
|
if (!this.injector.get(AuthService).user()) {
|
||||||
await this.router.navigate(['/login'], {
|
await this.router.navigate(['/login'], {
|
||||||
queryParams: { returnUrl: `/producto/${event.product.id}` },
|
queryParams: {
|
||||||
|
returnUrl: event.reservedInCart ? this.router.url : `/producto/${event.product.id}`,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -126,15 +138,25 @@ export class CategoryItemsPageComponent {
|
|||||||
|
|
||||||
this.creatingDirectPurchase.set(true);
|
this.creatingDirectPurchase.set(true);
|
||||||
try {
|
try {
|
||||||
const purchase = await this.injector.get(CheckoutService).startCheckout(tenant.codigo, {
|
const reservedCartId = event.reservedInCart ? (this.cartService.cart()?.id ?? null) : null;
|
||||||
direct_items: [
|
if (event.reservedInCart && reservedCartId === null) {
|
||||||
{
|
this.toastService.danger('No se pudo identificar el carrito reservado.');
|
||||||
catalog_item_id: event.product.id,
|
return;
|
||||||
variant_id: event.variant ?? null,
|
}
|
||||||
cantidad: event.quantity,
|
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 } });
|
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
@@ -145,14 +167,31 @@ export class CategoryItemsPageComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onAddToCart(event: ProductListCartEvent): void {
|
protected onAddToCart(event: ProductListCartEvent): void {
|
||||||
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).subscribe({
|
const productId = event.product.id;
|
||||||
next: (response) => {
|
if (this.savingProductIds().has(productId)) {
|
||||||
this.toastService.success(response.message || 'Producto agregado al carrito');
|
return;
|
||||||
},
|
}
|
||||||
error: (error: HttpErrorResponse) => {
|
|
||||||
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
|
this.setProductSaving(productId, true);
|
||||||
this.toastService.danger(message);
|
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;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -58,16 +58,23 @@
|
|||||||
[subtotal]="cartSubtotal()"
|
[subtotal]="cartSubtotal()"
|
||||||
[discount]="cartDiscount()"
|
[discount]="cartDiscount()"
|
||||||
[total]="cartTotal()"
|
[total]="cartTotal()"
|
||||||
[allowEditing]="
|
[readonly]="!canModifyCart()"
|
||||||
createdPurchase()?.status === 'created' || createdPurchase()?.status === 'pending_payment'
|
[allowModify]="true"
|
||||||
"
|
[showModifyWhenReadonly]="true"
|
||||||
[allowRemove]="false"
|
[allowUpdateQuantity]="canUpdateCartQuantity()"
|
||||||
|
[allowUpdateVariant]="canUpdateCartVariant()"
|
||||||
|
[requireEditingMode]="true"
|
||||||
|
[allowDelete]="canDeleteCartItems()"
|
||||||
[persistQuantityChanges]="false"
|
[persistQuantityChanges]="false"
|
||||||
|
[persistVariantChanges]="false"
|
||||||
|
[persistDeleteChanges]="false"
|
||||||
[editing]="isEditingItems()"
|
[editing]="isEditingItems()"
|
||||||
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"
|
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"
|
||||||
backgroundColor="transparent"
|
backgroundColor="transparent"
|
||||||
(editingChange)="onEditingItemsChange($event)"
|
(editingChange)="onEditingItemsChange($event)"
|
||||||
(itemQuantityChange)="onPurchaseItemQuantityChange($event)"
|
(itemQuantityChange)="onPurchaseItemQuantityChange($event)"
|
||||||
|
(itemVariantChange)="onPurchaseItemVariantChange($event)"
|
||||||
|
(itemRemove)="onPurchaseItemRemove($event)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
import { getTestBed, TestBed } from '@angular/core/testing';
|
import { getTestBed, TestBed } from '@angular/core/testing';
|
||||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||||
@@ -10,6 +11,8 @@ import { CartService } from '../../../../core/services/cart/cart.service';
|
|||||||
import { CheckoutService } from '../../../../core/services/checkout.service';
|
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
|
import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
|
||||||
import { CheckoutPageComponent } from './checkout-page.component';
|
import { CheckoutPageComponent } from './checkout-page.component';
|
||||||
|
|
||||||
describe('CheckoutPageComponent payment validation', () => {
|
describe('CheckoutPageComponent payment validation', () => {
|
||||||
@@ -17,11 +20,13 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
startCheckout: ReturnType<typeof vi.fn>;
|
startCheckout: ReturnType<typeof vi.fn>;
|
||||||
updateCustomerData: ReturnType<typeof vi.fn>;
|
updateCustomerData: ReturnType<typeof vi.fn>;
|
||||||
updateItemQuantity: ReturnType<typeof vi.fn>;
|
updateItemQuantity: ReturnType<typeof vi.fn>;
|
||||||
|
updateItemVariant: ReturnType<typeof vi.fn>;
|
||||||
|
removeItem: ReturnType<typeof vi.fn>;
|
||||||
prepareItemEditing: ReturnType<typeof vi.fn>;
|
prepareItemEditing: ReturnType<typeof vi.fn>;
|
||||||
cancelPurchase: ReturnType<typeof vi.fn>;
|
cancelPurchase: ReturnType<typeof vi.fn>;
|
||||||
generatePaymentIntent: ReturnType<typeof vi.fn>;
|
generatePaymentIntent: ReturnType<typeof vi.fn>;
|
||||||
getPurchase: ReturnType<typeof vi.fn>;
|
|
||||||
submitPurchaseForReview: ReturnType<typeof vi.fn>;
|
submitPurchaseForReview: ReturnType<typeof vi.fn>;
|
||||||
|
getPurchase: ReturnType<typeof vi.fn>;
|
||||||
withCustomLoading: ReturnType<typeof vi.fn>;
|
withCustomLoading: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
let cartServiceStub: {
|
let cartServiceStub: {
|
||||||
@@ -31,8 +36,15 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
clearCart: ReturnType<typeof vi.fn>;
|
clearCart: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
let routerStub: { navigate: ReturnType<typeof vi.fn> };
|
let routerStub: { navigate: ReturnType<typeof vi.fn> };
|
||||||
|
let toastServiceStub: { danger: ReturnType<typeof vi.fn> };
|
||||||
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
|
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
|
||||||
let authUserState: ReturnType<typeof signal>;
|
let authUserState: ReturnType<typeof signal>;
|
||||||
|
let tenantState: ReturnType<
|
||||||
|
typeof signal<{
|
||||||
|
codigo: string;
|
||||||
|
checkout_editing_policy?: CartEditingPolicy;
|
||||||
|
}>
|
||||||
|
>;
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
try {
|
try {
|
||||||
@@ -54,13 +66,15 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
}),
|
}),
|
||||||
updateCustomerData: vi.fn(),
|
updateCustomerData: vi.fn(),
|
||||||
updateItemQuantity: vi.fn(),
|
updateItemQuantity: vi.fn(),
|
||||||
|
updateItemVariant: vi.fn(),
|
||||||
|
removeItem: vi.fn(),
|
||||||
prepareItemEditing: vi.fn(),
|
prepareItemEditing: vi.fn(),
|
||||||
cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }),
|
cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }),
|
||||||
generatePaymentIntent: vi.fn().mockResolvedValue({
|
generatePaymentIntent: vi.fn().mockResolvedValue({
|
||||||
qr_data: { qr_code: 'qr-value' },
|
qr_data: { qr_code: 'qr-value' },
|
||||||
}),
|
}),
|
||||||
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
|
||||||
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||||
|
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||||
withCustomLoading: vi.fn(),
|
withCustomLoading: vi.fn(),
|
||||||
};
|
};
|
||||||
checkoutServiceStub.withCustomLoading.mockReturnValue(checkoutServiceStub);
|
checkoutServiceStub.withCustomLoading.mockReturnValue(checkoutServiceStub);
|
||||||
@@ -86,8 +100,19 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
routerStub = { navigate: vi.fn() };
|
routerStub = { navigate: vi.fn() };
|
||||||
|
toastServiceStub = { danger: vi.fn() };
|
||||||
routeQueryParamMap = convertToParamMap({});
|
routeQueryParamMap = convertToParamMap({});
|
||||||
authUserState = signal(null);
|
authUserState = signal(null);
|
||||||
|
tenantState = signal({
|
||||||
|
codigo: 'tenant-test',
|
||||||
|
checkout_editing_policy: {
|
||||||
|
code: 'full',
|
||||||
|
allow_modify: true,
|
||||||
|
allow_delete: true,
|
||||||
|
allow_update_quantity: true,
|
||||||
|
allow_update_variant: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [CheckoutPageComponent],
|
imports: [CheckoutPageComponent],
|
||||||
@@ -95,8 +120,9 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
{ provide: CheckoutService, useValue: checkoutServiceStub },
|
{ provide: CheckoutService, useValue: checkoutServiceStub },
|
||||||
{ provide: CatalogService, useValue: { getCatalogItem: vi.fn() } },
|
{ provide: CatalogService, useValue: { getCatalogItem: vi.fn() } },
|
||||||
{ provide: CartService, useValue: cartServiceStub },
|
{ provide: CartService, useValue: cartServiceStub },
|
||||||
{ provide: TenantService, useValue: { tenant: signal({ codigo: 'tenant-test' }) } },
|
{ provide: TenantService, useValue: { tenant: tenantState } },
|
||||||
{ provide: AuthService, useValue: { user: authUserState } },
|
{ provide: AuthService, useValue: { user: authUserState } },
|
||||||
|
{ provide: ToastService, useValue: toastServiceStub },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
useValue: {
|
useValue: {
|
||||||
@@ -194,46 +220,87 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('checks a transfer once and redirects to purchase status while pending', async () => {
|
it('polls a transfer every three seconds up to four attempts', async () => {
|
||||||
|
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
await component.onComplete();
|
await component.onComplete();
|
||||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
|
expect(component.transferValidationStatus()).toBe('checking');
|
||||||
expect(component.transferValidationStatus()).toBe('pending');
|
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
||||||
|
await vi.advanceTimersByTimeAsync(3_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(attempt);
|
||||||
|
expect(component.transferValidationStatus()).toBe('checking');
|
||||||
|
}
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(3_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
|
||||||
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(30_000);
|
|
||||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
|
|
||||||
|
|
||||||
await component.onComplete();
|
|
||||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('navigates after a transfer is confirmed as paid', async () => {
|
it('navigates after a transfer is confirmed as paid', async () => {
|
||||||
checkoutServiceStub.submitPurchaseForReview.mockResolvedValue({ status: 'paid' });
|
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'paid' });
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
await component.onComplete();
|
await component.onComplete();
|
||||||
|
await vi.advanceTimersByTimeAsync(3_000);
|
||||||
|
|
||||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows a retryable state when transfer validation fails', async () => {
|
it('keeps polling after transfer validation requests fail', async () => {
|
||||||
|
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
checkoutServiceStub.getPurchase.mockRejectedValue(new Error('network error'));
|
||||||
|
const { component } = createComponent();
|
||||||
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
|
await component.onComplete();
|
||||||
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||||
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not poll when submitting a transfer for review fails', async () => {
|
||||||
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error'));
|
checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error'));
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
await component.onComplete();
|
await component.onComplete();
|
||||||
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
|
||||||
|
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
});
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
|
||||||
|
it('cancels transfer polling when the payment method changes or the component is destroyed', async () => {
|
||||||
|
const first = createComponent();
|
||||||
|
first.component.selectedPaymentMethod.set('transfer');
|
||||||
|
first.component.onComplete();
|
||||||
|
checkoutServiceStub.generatePaymentIntent.mockResolvedValueOnce({});
|
||||||
|
await first.component.selectPaymentMethod('qr');
|
||||||
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
const second = createComponent();
|
||||||
|
second.component.selectedPaymentMethod.set('transfer');
|
||||||
|
second.component.onComplete();
|
||||||
|
second.fixture.destroy();
|
||||||
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('loads purchase items but prefills customer data from the user', async () => {
|
it('loads purchase items but prefills customer data from the user', async () => {
|
||||||
@@ -366,11 +433,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
|
|
||||||
expect(component.checkoutStepIndex()).toBe(1);
|
expect(component.checkoutStepIndex()).toBe(1);
|
||||||
expect(component.selectedPaymentMethod()).toBe('qr');
|
expect(component.selectedPaymentMethod()).toBe('qr');
|
||||||
expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledWith(
|
expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledWith('tenant-test', 25, 'qr');
|
||||||
'tenant-test',
|
|
||||||
25,
|
|
||||||
'qr',
|
|
||||||
);
|
|
||||||
expect(component.qrData()).toBe('qr-value');
|
expect(component.qrData()).toBe('qr-value');
|
||||||
expect(component.qrPaymentStatus()).toBe('waiting');
|
expect(component.qrPaymentStatus()).toBe('waiting');
|
||||||
});
|
});
|
||||||
@@ -439,7 +502,14 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
quantity: 3,
|
quantity: 3,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith('tenant-test', 25, 91, 3);
|
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith(
|
||||||
|
'tenant-test',
|
||||||
|
25,
|
||||||
|
91,
|
||||||
|
3,
|
||||||
|
null,
|
||||||
|
'purchase',
|
||||||
|
);
|
||||||
expect(component.createdPurchase()).toBe(updatedPurchase);
|
expect(component.createdPurchase()).toBe(updatedPurchase);
|
||||||
expect(component.isUpdatingItem()).toBe(false);
|
expect(component.isUpdatingItem()).toBe(false);
|
||||||
});
|
});
|
||||||
@@ -472,6 +542,60 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(component.isEditingItems()).toBe(false);
|
expect(component.isEditingItems()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('shows Modificar and returns to the home cart when checkout editing is disabled', async () => {
|
||||||
|
tenantState.set({
|
||||||
|
codigo: 'tenant-test',
|
||||||
|
checkout_editing_policy: {
|
||||||
|
code: 'disabled',
|
||||||
|
allow_modify: false,
|
||||||
|
allow_delete: false,
|
||||||
|
allow_update_quantity: false,
|
||||||
|
allow_update_variant: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const { fixture, component } = createComponent();
|
||||||
|
component.createdPurchase.set({
|
||||||
|
id: 25,
|
||||||
|
status: 'created',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: 91,
|
||||||
|
quantity: 2,
|
||||||
|
unit_price: '100.00',
|
||||||
|
line_total: '200.00',
|
||||||
|
source_catalog_item_id: 8,
|
||||||
|
source_variant_id: null,
|
||||||
|
item_details: {
|
||||||
|
nombre: 'Remera',
|
||||||
|
descripcion: null,
|
||||||
|
slug: 'remera',
|
||||||
|
imagen: null,
|
||||||
|
attributes: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
subtotal: '200.00',
|
||||||
|
total: '200.00',
|
||||||
|
});
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const modifyButton = (fixture.nativeElement as HTMLElement).querySelector('.cart-edit-btn');
|
||||||
|
expect(modifyButton?.textContent?.trim()).toBe('Modificar');
|
||||||
|
expect(
|
||||||
|
(fixture.nativeElement as HTMLElement).querySelector('app-quantity-selector'),
|
||||||
|
).toBeNull();
|
||||||
|
|
||||||
|
await component.onEditingItemsChange(true);
|
||||||
|
|
||||||
|
expect(component.canUpdateCartQuantity()).toBe(false);
|
||||||
|
expect(component.canModifyCart()).toBe(false);
|
||||||
|
expect(component.isEditingItems()).toBe(false);
|
||||||
|
expect(checkoutServiceStub.prepareItemEditing).not.toHaveBeenCalled();
|
||||||
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/'], {
|
||||||
|
queryParams: { openCart: true },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('updates customer data on the existing purchase before payment', async () => {
|
it('updates customer data on the existing purchase before payment', async () => {
|
||||||
const updatedPurchase = {
|
const updatedPurchase = {
|
||||||
id: 25,
|
id: 25,
|
||||||
@@ -506,14 +630,65 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(component.stepper.next).toHaveBeenCalledOnce();
|
expect(component.stepper.next).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('cancels the pending purchase before allowing navigation away', async () => {
|
it('keeps the checkout purchase intact when navigating away', async () => {
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
|
|
||||||
await expect(component.canDeactivate()).resolves.toBe(true);
|
await expect(component.canDeactivate()).resolves.toBe(true);
|
||||||
|
|
||||||
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
expect(checkoutServiceStub.cancelPurchase).not.toHaveBeenCalled();
|
||||||
expect(cartServiceStub.loadCart).toHaveBeenCalled();
|
expect(cartServiceStub.loadCart).toHaveBeenCalled();
|
||||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(component.createdPurchaseId()).toBeNull();
|
expect(component.createdPurchaseId()).toBe(25);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the API message and redirects home when a checkout operation finds an expired purchase', async () => {
|
||||||
|
checkoutServiceStub.generatePaymentIntent.mockRejectedValue(
|
||||||
|
new HttpErrorResponse({
|
||||||
|
status: 422,
|
||||||
|
error: {
|
||||||
|
code: 'purchase.expired',
|
||||||
|
message: 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { component } = createComponent();
|
||||||
|
|
||||||
|
await component.selectPaymentMethod('qr');
|
||||||
|
|
||||||
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
|
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
|
);
|
||||||
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/']);
|
||||||
|
expect(component.isGeneratingIntent()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats a generic customer-data error as expired when the local deadline passed', () => {
|
||||||
|
const { component } = createComponent();
|
||||||
|
component.createdPurchase.set({
|
||||||
|
id: 25,
|
||||||
|
status: 'created',
|
||||||
|
expires_at: new Date(Date.now() - 1_000).toISOString(),
|
||||||
|
items: [],
|
||||||
|
subtotal: '100.00',
|
||||||
|
total: '100.00',
|
||||||
|
});
|
||||||
|
|
||||||
|
const handled = component.handleCheckoutError(
|
||||||
|
new HttpErrorResponse({
|
||||||
|
status: 422,
|
||||||
|
error: {
|
||||||
|
errors: {
|
||||||
|
purchase: ['La compra ya no se puede modificar.'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
'No se pudieron actualizar los datos de la compra.',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(handled).toBe(true);
|
||||||
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
|
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
|
);
|
||||||
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/']);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
signal,
|
signal,
|
||||||
ViewChild,
|
ViewChild,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { FormBuilder, Validators } from '@angular/forms';
|
import { FormBuilder, Validators } from '@angular/forms';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { firstValueFrom, startWith } from 'rxjs';
|
import { firstValueFrom, startWith } from 'rxjs';
|
||||||
@@ -20,6 +21,7 @@ import {
|
|||||||
} from '../../../../core/services/checkout.service';
|
} from '../../../../core/services/checkout.service';
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import { BankAccount } from '../../../../core/services/tenant.interface';
|
import { BankAccount } from '../../../../core/services/tenant.interface';
|
||||||
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
|
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
|
||||||
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
||||||
@@ -36,6 +38,12 @@ import {
|
|||||||
TransferValidationStatus,
|
TransferValidationStatus,
|
||||||
} from './checkout-page.models';
|
} from './checkout-page.models';
|
||||||
|
|
||||||
|
interface ApiErrorResponse {
|
||||||
|
code?: string;
|
||||||
|
message?: string;
|
||||||
|
errors?: Record<string, string[]>;
|
||||||
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-checkout-page',
|
selector: 'app-checkout-page',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
@@ -59,11 +67,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
private readonly authService = inject(AuthService);
|
private readonly authService = inject(AuthService);
|
||||||
private readonly cartService = inject(CartService);
|
private readonly cartService = inject(CartService);
|
||||||
private readonly qrPollingIntervalMs = 5_000;
|
private readonly qrPollingIntervalMs = 5_000;
|
||||||
|
private readonly toastService = inject(ToastService);
|
||||||
private readonly qrPollingMaxAttempts = 9;
|
private readonly qrPollingMaxAttempts = 9;
|
||||||
|
private readonly transferPollingIntervalMs = 3_000;
|
||||||
|
private readonly transferPollingMaxAttempts = 4;
|
||||||
|
|
||||||
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
private qrPollingAttempts = 0;
|
private qrPollingAttempts = 0;
|
||||||
private qrPollingRunId = 0;
|
private qrPollingRunId = 0;
|
||||||
|
private transferPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private transferPollingAttempts = 0;
|
||||||
|
private transferPollingRunId = 0;
|
||||||
private paymentMethodRequestId = 0;
|
private paymentMethodRequestId = 0;
|
||||||
private navigationStarted = false;
|
private navigationStarted = false;
|
||||||
|
|
||||||
@@ -79,6 +93,18 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
|
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
|
||||||
protected readonly isLoadingPurchase = signal(true);
|
protected readonly isLoadingPurchase = signal(true);
|
||||||
protected readonly checkoutStepIndex = signal(0);
|
protected readonly checkoutStepIndex = signal(0);
|
||||||
|
protected readonly canUpdateCartQuantity = computed(
|
||||||
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_update_quantity ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canUpdateCartVariant = computed(
|
||||||
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_update_variant ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canDeleteCartItems = computed(
|
||||||
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_delete ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canModifyCart = computed(
|
||||||
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_modify ?? false,
|
||||||
|
);
|
||||||
|
|
||||||
protected readonly cartSubtotal = computed(() => {
|
protected readonly cartSubtotal = computed(() => {
|
||||||
const purchase = this.createdPurchase();
|
const purchase = this.createdPurchase();
|
||||||
@@ -101,7 +127,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly paymentMethods: ReadonlyArray<PaymentMethodOption> = [
|
protected readonly paymentMethods: ReadonlyArray<PaymentMethodOption> = [
|
||||||
{ id: 'qr', label: 'QR' },
|
{ id: 'qr', label: 'QR' },
|
||||||
{ id: 'transfer', label: 'Transferencia' },
|
{ id: 'transfer', label: 'Transferencia' },
|
||||||
{ id: 'telepagos', label: 'TelePagos' },
|
|
||||||
];
|
];
|
||||||
protected readonly selectedPaymentMethod = signal<PaymentMethod>('qr');
|
protected readonly selectedPaymentMethod = signal<PaymentMethod>('qr');
|
||||||
protected readonly copiedTransferField = signal<TransferField | null>(null);
|
protected readonly copiedTransferField = signal<TransferField | null>(null);
|
||||||
@@ -156,6 +181,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
ngOnDestroy(): void {
|
ngOnDestroy(): void {
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
}
|
}
|
||||||
|
|
||||||
private mapPurchaseItemToMock(item: PurchaseDetailItemResponse): CartItemMock {
|
private mapPurchaseItemToMock(item: PurchaseDetailItemResponse): CartItemMock {
|
||||||
@@ -171,6 +197,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
value: attribute.value === null ? '' : String(attribute.value),
|
value: attribute.value === null ? '' : String(attribute.value),
|
||||||
})),
|
})),
|
||||||
quantity: item.quantity,
|
quantity: item.quantity,
|
||||||
|
variantId: item.source_variant_id,
|
||||||
|
variants: item.variants,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,6 +207,32 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (editing && !this.canModifyCart()) {
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
const purchaseId = this.createdPurchaseId();
|
||||||
|
|
||||||
|
if (!tenant || !purchaseId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isPreparingItemEdit.set(true);
|
||||||
|
try {
|
||||||
|
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
|
||||||
|
this.createdPurchaseId.set(null);
|
||||||
|
this.createdPurchase.set(null);
|
||||||
|
await firstValueFrom(this.cartService.loadCart());
|
||||||
|
await this.router.navigate(['/'], {
|
||||||
|
queryParams: { openCart: true },
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
this.handleCheckoutError(error, 'No se pudo restaurar el carrito para editarlo.');
|
||||||
|
} finally {
|
||||||
|
this.isPreparingItemEdit.set(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!editing) {
|
if (!editing) {
|
||||||
this.isEditingItems.set(false);
|
this.isEditingItems.set(false);
|
||||||
|
|
||||||
@@ -191,6 +245,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
this.isEditingItems.set(true);
|
this.isEditingItems.set(true);
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
this.qrData.set(null);
|
this.qrData.set(null);
|
||||||
this.qrPaymentStatus.set('idle');
|
this.qrPaymentStatus.set('idle');
|
||||||
this.transferAccount.set(null);
|
this.transferAccount.set(null);
|
||||||
@@ -209,7 +264,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
const purchase = await this.checkoutService.prepareItemEditing(tenant.codigo, purchaseId);
|
const purchase = await this.checkoutService.prepareItemEditing(tenant.codigo, purchaseId);
|
||||||
this.createdPurchase.set(purchase);
|
this.createdPurchase.set(purchase);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to prepare purchase item editing:', error);
|
this.handleCheckoutError(error, 'No se pudo preparar la compra para editarla.');
|
||||||
this.isEditingItems.set(false);
|
this.isEditingItems.set(false);
|
||||||
} finally {
|
} finally {
|
||||||
this.isPreparingItemEdit.set(false);
|
this.isPreparingItemEdit.set(false);
|
||||||
@@ -224,7 +279,14 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
const purchaseId = this.createdPurchaseId();
|
const purchaseId = this.createdPurchaseId();
|
||||||
const itemId = event.item.cartItemId;
|
const itemId = event.item.cartItemId;
|
||||||
|
|
||||||
if (!tenant || !purchaseId || !itemId || this.isUpdatingItem() || !this.isEditingItems()) {
|
if (
|
||||||
|
!this.canUpdateCartQuantity() ||
|
||||||
|
!tenant ||
|
||||||
|
!purchaseId ||
|
||||||
|
!itemId ||
|
||||||
|
this.isUpdatingItem() ||
|
||||||
|
!this.isEditingItems()
|
||||||
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,10 +297,85 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
purchaseId,
|
purchaseId,
|
||||||
itemId,
|
itemId,
|
||||||
event.quantity,
|
event.quantity,
|
||||||
|
this.createdPurchase()?.cart_id ?? null,
|
||||||
|
this.createdPurchase()?.items_source ?? 'purchase',
|
||||||
);
|
);
|
||||||
this.createdPurchase.set(purchase);
|
this.createdPurchase.set(purchase);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to update purchase item quantity:', error);
|
this.handleCheckoutError(error, 'No se pudo actualizar la cantidad del producto.');
|
||||||
|
} finally {
|
||||||
|
this.isUpdatingItem.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async onPurchaseItemVariantChange(event: {
|
||||||
|
item: CartItemMock;
|
||||||
|
variantId: number;
|
||||||
|
}): Promise<void> {
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
const purchase = this.createdPurchase();
|
||||||
|
const itemId = event.item.cartItemId;
|
||||||
|
|
||||||
|
if (
|
||||||
|
!this.canUpdateCartVariant() ||
|
||||||
|
!tenant ||
|
||||||
|
!purchase ||
|
||||||
|
!itemId ||
|
||||||
|
this.isUpdatingItem() ||
|
||||||
|
!this.isEditingItems()
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isUpdatingItem.set(true);
|
||||||
|
try {
|
||||||
|
this.createdPurchase.set(
|
||||||
|
await this.checkoutService.updateItemVariant(
|
||||||
|
tenant.codigo,
|
||||||
|
purchase.id,
|
||||||
|
itemId,
|
||||||
|
event.variantId,
|
||||||
|
event.item.quantity,
|
||||||
|
purchase.cart_id,
|
||||||
|
purchase.items_source,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
this.handleCheckoutError(error, 'No se pudo actualizar la variante del producto.');
|
||||||
|
} finally {
|
||||||
|
this.isUpdatingItem.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async onPurchaseItemRemove(event: { item: CartItemMock }): Promise<void> {
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
const purchase = this.createdPurchase();
|
||||||
|
const itemId = event.item.cartItemId;
|
||||||
|
|
||||||
|
if (
|
||||||
|
!this.canDeleteCartItems() ||
|
||||||
|
!tenant ||
|
||||||
|
!purchase ||
|
||||||
|
!itemId ||
|
||||||
|
this.isUpdatingItem() ||
|
||||||
|
!this.isEditingItems()
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isUpdatingItem.set(true);
|
||||||
|
try {
|
||||||
|
this.createdPurchase.set(
|
||||||
|
await this.checkoutService.removeItem(
|
||||||
|
tenant.codigo,
|
||||||
|
purchase.id,
|
||||||
|
itemId,
|
||||||
|
purchase.cart_id,
|
||||||
|
purchase.items_source,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
this.handleCheckoutError(error, 'No se pudo eliminar el producto de la compra.');
|
||||||
} finally {
|
} finally {
|
||||||
this.isUpdatingItem.set(false);
|
this.isUpdatingItem.set(false);
|
||||||
}
|
}
|
||||||
@@ -268,8 +405,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
// Auto trigger intent for default option
|
// Auto trigger intent for default option
|
||||||
void this.selectPaymentMethod(this.selectedPaymentMethod());
|
void this.selectPaymentMethod(this.selectedPaymentMethod());
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create purchase:', error);
|
this.handleCheckoutError(error, 'No se pudieron actualizar los datos de la compra.');
|
||||||
// Here we could show an alert or toast
|
|
||||||
} finally {
|
} finally {
|
||||||
this.isUpdatingPurchase.set(false);
|
this.isUpdatingPurchase.set(false);
|
||||||
}
|
}
|
||||||
@@ -283,34 +419,21 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
public async canDeactivate(): Promise<boolean> {
|
public async canDeactivate(): Promise<boolean> {
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
|
|
||||||
if (this.navigationStarted) {
|
if (this.navigationStarted) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const purchaseId = this.createdPurchaseId();
|
// The checkout cart remains attached to its purchase. Once the user adds a
|
||||||
const tenant = this.tenantService.tenant();
|
// new item, the cart API creates a separate active cart automatically.
|
||||||
|
|
||||||
if (!purchaseId || !tenant) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
|
await firstValueFrom(this.cartService.loadCart());
|
||||||
this.createdPurchaseId.set(null);
|
|
||||||
this.createdPurchase.set(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await firstValueFrom(this.cartService.loadCart());
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to restore cart after cancelling checkout:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to cancel purchase:', error);
|
console.error('Failed to load the active cart after leaving checkout:', error);
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
|
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
|
||||||
@@ -319,6 +442,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
this.qrPaymentStatus.set('idle');
|
this.qrPaymentStatus.set('idle');
|
||||||
this.transferValidationStatus.set('idle');
|
this.transferValidationStatus.set('idle');
|
||||||
this.selectedPaymentMethod.set(method);
|
this.selectedPaymentMethod.set(method);
|
||||||
@@ -331,7 +455,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
const purchaseId = this.createdPurchaseId();
|
const purchaseId = this.createdPurchaseId();
|
||||||
const tenant = this.tenantService.tenant();
|
const tenant = this.tenantService.tenant();
|
||||||
|
|
||||||
if (!purchaseId || !tenant || method === 'telepagos') {
|
if (!purchaseId || !tenant) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -357,7 +481,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.startQrPolling();
|
this.startQrPolling();
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to generate payment intent:', error);
|
this.handleCheckoutError(error, 'No se pudo generar la intenci\u00f3n de pago.');
|
||||||
} finally {
|
} finally {
|
||||||
this.isGeneratingIntent.set(false);
|
this.isGeneratingIntent.set(false);
|
||||||
}
|
}
|
||||||
@@ -376,6 +500,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.transferDni.set(dni);
|
this.transferDni.set(dni);
|
||||||
|
this.stopTransferPolling();
|
||||||
this.transferValidationStatus.set('idle');
|
this.transferValidationStatus.set('idle');
|
||||||
this.isGeneratingIntent.set(true);
|
this.isGeneratingIntent.set(true);
|
||||||
try {
|
try {
|
||||||
@@ -393,7 +518,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to generate transfer payment intent:', error);
|
this.handleCheckoutError(error, 'No se pudo generar la intenci\u00f3n de transferencia.');
|
||||||
} finally {
|
} finally {
|
||||||
this.isGeneratingIntent.set(false);
|
this.isGeneratingIntent.set(false);
|
||||||
}
|
}
|
||||||
@@ -430,26 +555,97 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.stopTransferPolling();
|
||||||
this.transferValidationStatus.set('checking');
|
this.transferValidationStatus.set('checking');
|
||||||
|
this.transferPollingAttempts = 0;
|
||||||
|
|
||||||
|
const runId = this.transferPollingRunId;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const purchase = await this.checkoutService
|
const purchase = await this.checkoutService
|
||||||
.withCustomLoading()
|
.withCustomLoading()
|
||||||
.submitPurchaseForReview(tenant.codigo, purchaseId);
|
.submitPurchaseForReview(tenant.codigo, purchaseId);
|
||||||
|
|
||||||
if (purchase.status === 'paid' || purchase.status === 'pending_payment') {
|
if (runId !== this.transferPollingRunId) {
|
||||||
if (purchase.status === 'pending_payment') {
|
return;
|
||||||
this.transferValidationStatus.set('pending');
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
if (purchase.status === 'paid') {
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.transferValidationStatus.set('error');
|
this.scheduleTransferPoll(runId);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to submit purchase for review:', error);
|
const expired = this.handleCheckoutError(
|
||||||
|
error,
|
||||||
|
'No se pudo enviar la compra a revisi\u00f3n.',
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!expired && runId === this.transferPollingRunId) {
|
||||||
|
this.transferValidationStatus.set('error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleTransferPoll(runId: number): void {
|
||||||
|
this.transferPollingTimeoutId = setTimeout(() => {
|
||||||
|
this.transferPollingTimeoutId = null;
|
||||||
|
void this.checkTransferPayment(runId);
|
||||||
|
}, this.transferPollingIntervalMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async checkTransferPayment(runId: number): Promise<void> {
|
||||||
|
if (runId !== this.transferPollingRunId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const purchaseId = this.createdPurchaseId();
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
|
||||||
|
if (!purchaseId || !tenant || this.selectedPaymentMethod() !== 'transfer') {
|
||||||
|
this.stopTransferPolling();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.transferPollingAttempts += 1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const purchase = await this.checkoutService
|
||||||
|
.withCustomLoading()
|
||||||
|
.getPurchase(tenant.codigo, purchaseId);
|
||||||
|
|
||||||
|
if (runId !== this.transferPollingRunId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (purchase.status === 'paid') {
|
||||||
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to validate transfer payment:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (runId !== this.transferPollingRunId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.transferPollingAttempts >= this.transferPollingMaxAttempts) {
|
||||||
|
this.stopTransferPolling();
|
||||||
this.transferValidationStatus.set('error');
|
this.transferValidationStatus.set('error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.scheduleTransferPoll(runId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private stopTransferPolling(): void {
|
||||||
|
this.transferPollingRunId += 1;
|
||||||
|
|
||||||
|
if (this.transferPollingTimeoutId !== null) {
|
||||||
|
clearTimeout(this.transferPollingTimeoutId);
|
||||||
|
this.transferPollingTimeoutId = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -563,6 +759,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
this.navigationStarted = true;
|
this.navigationStarted = true;
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
|
|
||||||
void this.router.navigate(['/checkout/status', purchaseId]);
|
void this.router.navigate(['/checkout/status', purchaseId]);
|
||||||
}
|
}
|
||||||
@@ -617,4 +814,54 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
void this.router.navigate(['/']);
|
void this.router.navigate(['/']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
|
||||||
|
if (!(error instanceof HttpErrorResponse)) {
|
||||||
|
this.toastService.danger(fallbackMessage);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = error.error as ApiErrorResponse | null;
|
||||||
|
|
||||||
|
if (response?.code === 'purchase.expired' || this.hasExpiredPurchase()) {
|
||||||
|
this.navigationStarted = true;
|
||||||
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
|
this.toastService.danger(
|
||||||
|
response?.code === 'purchase.expired' && response.message
|
||||||
|
? response.message
|
||||||
|
: 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
|
);
|
||||||
|
void this.router.navigate(['/']);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const validationMessage = response?.errors
|
||||||
|
? Object.values(response.errors).flat().find(Boolean)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
this.toastService.danger(validationMessage ?? response?.message ?? fallbackMessage);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private hasExpiredPurchase(): boolean {
|
||||||
|
const purchase = this.createdPurchase();
|
||||||
|
|
||||||
|
if (!purchase) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (purchase.status === 'expired') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!purchase.expires_at) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Date.parse(purchase.expires_at) <= Date.now();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { FormControl, FormGroup } from '@angular/forms';
|
import { FormControl, FormGroup } from '@angular/forms';
|
||||||
|
|
||||||
export type PaymentMethod = 'qr' | 'transfer' | 'telepagos';
|
export type PaymentMethod = 'qr' | 'transfer';
|
||||||
export type TransferField = 'cvu' | 'alias';
|
export type TransferField = 'cvu' | 'alias';
|
||||||
export type QrPaymentStatus = 'idle' | 'waiting' | 'timed_out' | 'failed';
|
export type QrPaymentStatus = 'idle' | 'waiting' | 'timed_out' | 'failed';
|
||||||
export type TransferValidationStatus = 'idle' | 'checking' | 'pending' | 'error';
|
export type TransferValidationStatus = 'idle' | 'checking' | 'error';
|
||||||
|
|
||||||
export interface PaymentMethodOption {
|
export interface PaymentMethodOption {
|
||||||
id: PaymentMethod;
|
id: PaymentMethod;
|
||||||
|
|||||||
@@ -18,14 +18,7 @@
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<span class="payment-method__label">
|
<span class="payment-method__label">
|
||||||
@if (method.id === 'telepagos') {
|
{{ method.label }}
|
||||||
<span class="telepagos-logo" aria-label="TelePagos">
|
|
||||||
<span class="telepagos-logo__tele">tele</span
|
|
||||||
><span class="telepagos-logo__pagos">pagos</span>
|
|
||||||
</span>
|
|
||||||
} @else {
|
|
||||||
{{ method.label }}
|
|
||||||
}
|
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
<i class="fa-solid fa-angle-right payment-method__chevron" aria-hidden="true"></i>
|
<i class="fa-solid fa-angle-right payment-method__chevron" aria-hidden="true"></i>
|
||||||
@@ -59,8 +52,6 @@
|
|||||||
(submitDni)="generateTransferIntent.emit($event)"
|
(submitDni)="generateTransferIntent.emit($event)"
|
||||||
(completePurchase)="complete.emit()"
|
(completePurchase)="complete.emit()"
|
||||||
/>
|
/>
|
||||||
} @else {
|
|
||||||
<app-checkout-payment-telepagos />
|
|
||||||
}
|
}
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -101,26 +101,13 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.telepagos-logo {
|
|
||||||
display: inline-block;
|
|
||||||
font-size: 1.45rem;
|
|
||||||
font-weight: 800;
|
|
||||||
line-height: 1;
|
|
||||||
letter-spacing: -0.03em;
|
|
||||||
background: linear-gradient(90deg, #0a69d8 0 78%, #f6a11a 78% 100%);
|
|
||||||
-webkit-background-clip: text;
|
|
||||||
background-clip: text;
|
|
||||||
color: transparent;
|
|
||||||
}
|
|
||||||
|
|
||||||
.payment-panel {
|
.payment-panel {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
|
|
||||||
> app-checkout-payment-qr,
|
> app-checkout-payment-qr,
|
||||||
> app-checkout-payment-transfer,
|
> app-checkout-payment-transfer {
|
||||||
> app-checkout-payment-telepagos {
|
|
||||||
display: block;
|
display: block;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 320px;
|
max-width: 320px;
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { ChangeDetectionStrategy, Component, input, output } from '@angular/core';
|
import { ChangeDetectionStrategy, Component, input, output } from '@angular/core';
|
||||||
|
|
||||||
import { CheckoutPaymentQrComponent } from './components/checkout-payment-qr/checkout-payment-qr.component';
|
import { CheckoutPaymentQrComponent } from './components/checkout-payment-qr/checkout-payment-qr.component';
|
||||||
import { CheckoutPaymentTelepagosComponent } from './components/checkout-payment-telepagos/checkout-payment-telepagos.component';
|
|
||||||
import { CheckoutPaymentTransferComponent } from './components/checkout-payment-transfer/checkout-payment-transfer.component';
|
import { CheckoutPaymentTransferComponent } from './components/checkout-payment-transfer/checkout-payment-transfer.component';
|
||||||
import {
|
import {
|
||||||
PaymentMethod,
|
PaymentMethod,
|
||||||
@@ -15,7 +14,7 @@ import {
|
|||||||
@Component({
|
@Component({
|
||||||
selector: 'app-checkout-payment-step',
|
selector: 'app-checkout-payment-step',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [CheckoutPaymentQrComponent, CheckoutPaymentTelepagosComponent, CheckoutPaymentTransferComponent],
|
imports: [CheckoutPaymentQrComponent, CheckoutPaymentTransferComponent],
|
||||||
templateUrl: './checkout-payment-step.component.html',
|
templateUrl: './checkout-payment-step.component.html',
|
||||||
styleUrl: './checkout-payment-step.component.scss',
|
styleUrl: './checkout-payment-step.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush
|
changeDetection: ChangeDetectionStrategy.OnPush
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
<div class="payment-panel__card">
|
|
||||||
<h3 class="payment-panel__title">Descarga la app de TelePagos para finalizar la compra</h3>
|
|
||||||
<div class="payment-panel__divider"></div>
|
|
||||||
|
|
||||||
<div class="store-badges" aria-label="Tiendas disponibles">
|
|
||||||
<div class="store-badge">
|
|
||||||
<i class="fa-brands fa-google-play" aria-hidden="true"></i>
|
|
||||||
<span class="store-badge__text">
|
|
||||||
<small>Disponible en</small>
|
|
||||||
<strong>Google Play</strong>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="store-badge">
|
|
||||||
<i class="fa-brands fa-apple" aria-hidden="true"></i>
|
|
||||||
<span class="store-badge__text">
|
|
||||||
<small>Descargalo en</small>
|
|
||||||
<strong>App Store</strong>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
.payment-panel__card {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 320px;
|
|
||||||
min-height: 269px;
|
|
||||||
padding: 1.5rem 1.75rem;
|
|
||||||
border-radius: 5px;
|
|
||||||
background: #ffffff;
|
|
||||||
color: #666666;
|
|
||||||
box-shadow: 0 0 0 1px #f1f1f1;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.payment-panel__title {
|
|
||||||
max-width: 18rem;
|
|
||||||
margin: 0;
|
|
||||||
color: #8a8a8a;
|
|
||||||
font-size: 13px;
|
|
||||||
font-weight: 700;
|
|
||||||
line-height: 1.35;
|
|
||||||
}
|
|
||||||
|
|
||||||
.payment-panel__divider {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 220px;
|
|
||||||
height: 1px;
|
|
||||||
margin: 1.2rem 0 1.45rem;
|
|
||||||
background: #dddddd;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-badges {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 210px;
|
|
||||||
display: grid;
|
|
||||||
gap: 0.8rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-badge {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 0.75rem;
|
|
||||||
padding: 0.75rem 0.95rem;
|
|
||||||
border-radius: 0.85rem;
|
|
||||||
background: #111111;
|
|
||||||
color: #ffffff;
|
|
||||||
box-shadow: 0 10px 24px rgba(17, 17, 17, 0.16);
|
|
||||||
|
|
||||||
i {
|
|
||||||
font-size: 1.35rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
&__text {
|
|
||||||
display: grid;
|
|
||||||
text-align: left;
|
|
||||||
line-height: 1.1;
|
|
||||||
|
|
||||||
small {
|
|
||||||
font-size: 0.62rem;
|
|
||||||
letter-spacing: 0.05em;
|
|
||||||
text-transform: uppercase;
|
|
||||||
opacity: 0.8;
|
|
||||||
}
|
|
||||||
|
|
||||||
strong {
|
|
||||||
font-size: 1rem;
|
|
||||||
font-weight: 700;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { ChangeDetectionStrategy, Component } from '@angular/core';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'app-checkout-payment-telepagos',
|
|
||||||
standalone: true,
|
|
||||||
imports: [],
|
|
||||||
templateUrl: './checkout-payment-telepagos.component.html',
|
|
||||||
styleUrl: './checkout-payment-telepagos.component.scss',
|
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush
|
|
||||||
})
|
|
||||||
export class CheckoutPaymentTelepagosComponent {}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<div class="payment-panel__card">
|
<div class="payment-panel__card">
|
||||||
@if (validationStatus() === 'pending' || validationStatus() === 'error') {
|
@if (validationStatus() === 'error') {
|
||||||
<app-payment-verification-error
|
<app-payment-verification-error
|
||||||
[paymentAmount]="paymentAmount()"
|
[paymentAmount]="paymentAmount()"
|
||||||
[whatsappUrl]="whatsappUrl()"
|
[whatsappUrl]="whatsappUrl()"
|
||||||
@@ -102,5 +102,12 @@
|
|||||||
</app-button>
|
</app-button>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@if (validationStatus() === 'checking') {
|
||||||
|
<div class="payment-verification" role="status" aria-live="polite">
|
||||||
|
<span class="payment-verification__spinner" aria-hidden="true"></span>
|
||||||
|
<span class="payment-verification__message">Verificando pago</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
.payment-panel__card {
|
.payment-panel__card {
|
||||||
|
position: relative;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 320px;
|
max-width: 320px;
|
||||||
min-height: 400px;
|
min-height: 400px;
|
||||||
@@ -13,6 +14,40 @@
|
|||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.payment-verification {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 2;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 0.45rem;
|
||||||
|
border-radius: inherit;
|
||||||
|
background: rgba(255, 255, 255, 0.82);
|
||||||
|
|
||||||
|
&__spinner {
|
||||||
|
width: 30px;
|
||||||
|
height: 30px;
|
||||||
|
border: 4px solid rgba(17, 17, 17, 0.2);
|
||||||
|
border-top-color: #111111;
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: payment-verification-spin 0.75s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__message {
|
||||||
|
color: #111111;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes payment-verification-spin {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.payment-panel__title {
|
.payment-panel__title {
|
||||||
max-width: 18rem;
|
max-width: 18rem;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { getTestBed, TestBed } from '@angular/core/testing';
|
||||||
|
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||||
|
import { beforeAll, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { CheckoutPaymentTransferComponent } from './checkout-payment-transfer.component';
|
||||||
|
|
||||||
|
describe('CheckoutPaymentTransferComponent', () => {
|
||||||
|
beforeAll(() => {
|
||||||
|
try {
|
||||||
|
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
|
||||||
|
} catch {
|
||||||
|
// Test environment may already be initialized by another setup entrypoint.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders the payment verification overlay while checking the transfer', async () => {
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [CheckoutPaymentTransferComponent],
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
|
||||||
|
fixture.componentRef.setInput('validationStatus', 'checking');
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const overlay = fixture.nativeElement.querySelector('.payment-verification') as HTMLElement;
|
||||||
|
expect(overlay).not.toBeNull();
|
||||||
|
expect(overlay.textContent).toContain('Verificando pago');
|
||||||
|
expect(overlay.querySelector('.payment-verification__spinner')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the QR payment error and WhatsApp action when validation fails', async () => {
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [CheckoutPaymentTransferComponent],
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
|
||||||
|
fixture.componentRef.setInput('validationStatus', 'error');
|
||||||
|
fixture.componentRef.setInput('paymentAmount', 300000);
|
||||||
|
fixture.componentRef.setInput('whatsappUrl', 'https://wa.me/543412602222');
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
const whatsapp = Array.from(element.querySelectorAll('button')).find((button) =>
|
||||||
|
button.textContent?.includes('WhatsApp'),
|
||||||
|
);
|
||||||
|
expect(element.textContent).toMatch(/No pudimos verificar el pago de \$\s*300\.000\./);
|
||||||
|
expect(whatsapp).toBeDefined();
|
||||||
|
expect(element.querySelector('.payment-verification')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -63,7 +63,9 @@
|
|||||||
[disabled]="!selectedVariantAvailable() || variantLoading() || addingToCart()"
|
[disabled]="!selectedVariantAvailable() || variantLoading() || addingToCart()"
|
||||||
(click)="addToCart()"
|
(click)="addToCart()"
|
||||||
>
|
>
|
||||||
@if (variantLoading() || addingToCart()) {
|
@if (addingToCart()) {
|
||||||
|
Guardando
|
||||||
|
} @else if (variantLoading()) {
|
||||||
<div class="spinner-border spinner-border-sm" role="status"></div>
|
<div class="spinner-border spinner-border-sm" role="status"></div>
|
||||||
} @else {
|
} @else {
|
||||||
Agregar al carrito
|
Agregar al carrito
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
@@ -36,7 +37,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
has_tickets: false,
|
has_tickets: false,
|
||||||
minimum_use_date: null,
|
minimum_use_date: null,
|
||||||
maximum_use_date: null,
|
maximum_use_date: null,
|
||||||
stock_tecnico: 10,
|
maximum_addable_quantity: 10,
|
||||||
attributes: [],
|
attributes: [],
|
||||||
variants: [],
|
variants: [],
|
||||||
};
|
};
|
||||||
@@ -190,10 +191,10 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
const detailProduct: CatalogItemDetail = {
|
const detailProduct: CatalogItemDetail = {
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
images: ['https://example.com/product.png'],
|
images: ['https://example.com/product.png'],
|
||||||
variants: [{ id: 123, stock_tecnico: 10, values: {} }],
|
variants: [{ id: 123, maximum_addable_quantity: 10, values: {} }],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 10,
|
maximum_addable_quantity: 10,
|
||||||
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
|
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -294,10 +295,12 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
variants: [{ id: 123, stock_tecnico: 10, values: { color: 'beige', material: 'Cuero' } }],
|
variants: [
|
||||||
|
{ id: 123, maximum_addable_quantity: 10, values: { color: 'beige', material: 'Cuero' } },
|
||||||
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 10,
|
maximum_addable_quantity: 10,
|
||||||
images: ['https://example.com/variant1.png'],
|
images: ['https://example.com/variant1.png'],
|
||||||
values: {
|
values: {
|
||||||
color: 'beige',
|
color: 'beige',
|
||||||
@@ -334,8 +337,8 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
purpose: 'entry',
|
purpose: 'entry',
|
||||||
has_tickets: true,
|
has_tickets: true,
|
||||||
variants: [
|
variants: [
|
||||||
{ id: 101, event_date_id: 20, stock_tecnico: 10, values: { event_date: '20' } },
|
{ id: 101, event_date_id: 20, maximum_addable_quantity: 10, values: { event_date: '20' } },
|
||||||
{ id: 102, event_date_id: 21, stock_tecnico: 10, values: { event_date: '21' } },
|
{ id: 102, event_date_id: 21, maximum_addable_quantity: 10, values: { event_date: '21' } },
|
||||||
],
|
],
|
||||||
attributes: [
|
attributes: [
|
||||||
{
|
{
|
||||||
@@ -366,7 +369,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 101,
|
id: 101,
|
||||||
event_date_id: 20,
|
event_date_id: 20,
|
||||||
stock_tecnico: 10,
|
maximum_addable_quantity: 10,
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -410,7 +413,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
|
|
||||||
fixture.componentInstance['selectedVariant'].set({
|
fixture.componentInstance['selectedVariant'].set({
|
||||||
id: 1,
|
id: 1,
|
||||||
stock_tecnico: 10,
|
maximum_addable_quantity: 10,
|
||||||
values: {},
|
values: {},
|
||||||
});
|
});
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -493,19 +496,45 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('shows the backend purchase-limit message for a direct checkout', async () => {
|
||||||
|
checkoutServiceStub.startCheckout.mockRejectedValue(
|
||||||
|
new HttpErrorResponse({
|
||||||
|
status: 422,
|
||||||
|
error: {
|
||||||
|
code: 'purchase.limit_exceeded',
|
||||||
|
message: 'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
|
||||||
|
maximum_addable_quantity: 2,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await configureTestingModule();
|
||||||
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
const buyButton = Array.from(fixture.nativeElement.querySelectorAll('app-button button')).find(
|
||||||
|
(button) => button.textContent?.trim() === 'Comprar',
|
||||||
|
) as HTMLButtonElement;
|
||||||
|
|
||||||
|
buyButton.click();
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
|
'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('calls CartService.addItem when variant is selected and Add to Cart is clicked', async () => {
|
it('calls CartService.addItem when variant is selected and Add to Cart is clicked', async () => {
|
||||||
const detailProduct: CatalogItemDetail = {
|
const detailProduct: CatalogItemDetail = {
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
variants: [
|
variants: [
|
||||||
{
|
{
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 5,
|
maximum_addable_quantity: 5,
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 5,
|
maximum_addable_quantity: 5,
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -538,7 +567,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
resolveProduct({
|
resolveProduct({
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
variants: [],
|
variants: [],
|
||||||
stock_tecnico: 4,
|
maximum_addable_quantity: 4,
|
||||||
});
|
});
|
||||||
|
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
@@ -564,13 +593,13 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
variants: [
|
variants: [
|
||||||
{
|
{
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 5,
|
maximum_addable_quantity: 5,
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 5,
|
maximum_addable_quantity: 5,
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -602,7 +631,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
it('allows unlimited variants to increase quantity without a maximum', async () => {
|
it('allows unlimited variants to increase quantity without a maximum', async () => {
|
||||||
const unlimitedVariant = {
|
const unlimitedVariant = {
|
||||||
id: 321,
|
id: 321,
|
||||||
stock_tecnico: null,
|
maximum_addable_quantity: null,
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
@@ -610,7 +639,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
inventory_policy: 'unlimited',
|
inventory_policy: 'unlimited',
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 321,
|
id: 321,
|
||||||
stock_tecnico: null,
|
maximum_addable_quantity: null,
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -634,7 +663,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
it('caps an unlimited variant at the per-user purchase limit', async () => {
|
it('caps an unlimited variant at the per-user purchase limit', async () => {
|
||||||
const unlimitedVariant = {
|
const unlimitedVariant = {
|
||||||
id: 322,
|
id: 322,
|
||||||
stock_tecnico: null,
|
maximum_addable_quantity: 2,
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
@@ -643,7 +672,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
max_units_per_user: 2,
|
max_units_per_user: 2,
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 322,
|
id: 322,
|
||||||
stock_tecnico: null,
|
maximum_addable_quantity: 2,
|
||||||
images: [],
|
images: [],
|
||||||
values: { event_date: '20' },
|
values: { event_date: '20' },
|
||||||
},
|
},
|
||||||
@@ -667,14 +696,14 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
it('disables purchase actions for tracked variants without stock', async () => {
|
it('disables purchase actions for tracked variants without stock', async () => {
|
||||||
const trackedVariant = {
|
const trackedVariant = {
|
||||||
id: 654,
|
id: 654,
|
||||||
stock_tecnico: 0,
|
maximum_addable_quantity: 0,
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 654,
|
id: 654,
|
||||||
stock_tecnico: 0,
|
maximum_addable_quantity: 0,
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -98,27 +98,23 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
const variant = this.selectedVariant();
|
const variant = this.selectedVariant();
|
||||||
if (!prod) return 0;
|
if (!prod) return 0;
|
||||||
|
|
||||||
const stockLimit = variant
|
return variant
|
||||||
? variant.stock_tecnico
|
? (variant.maximum_addable_quantity ?? null)
|
||||||
: prod.variants.length === 0
|
: prod.variants.length === 0
|
||||||
? (prod.stock_tecnico ?? null)
|
? (prod.maximum_addable_quantity ?? null)
|
||||||
: 0;
|
: 0;
|
||||||
const userLimit = prod.max_units_per_user ?? null;
|
|
||||||
|
|
||||||
if (stockLimit === null) return userLimit;
|
|
||||||
if (userLimit === null) return stockLimit;
|
|
||||||
return Math.min(stockLimit, userLimit);
|
|
||||||
});
|
});
|
||||||
protected readonly selectedVariantAvailable = computed(() => {
|
protected readonly selectedVariantAvailable = computed(() => {
|
||||||
const prod = this.product();
|
const prod = this.product();
|
||||||
if (!prod) return false;
|
if (!prod) return false;
|
||||||
|
if (this.selectedVariantMax() === 0) return false;
|
||||||
|
|
||||||
const variant = this.selectedVariant();
|
const variant = this.selectedVariant();
|
||||||
if (variant) return this.isVariantAvailable(variant, prod);
|
if (variant) return this.isVariantAvailable(variant);
|
||||||
if (prod.purpose === 'entry') return false;
|
if (prod.purpose === 'entry') return false;
|
||||||
if (prod.variants.length > 0) return false;
|
if (prod.variants.length > 0) return false;
|
||||||
|
|
||||||
return prod.inventory_policy === 'unlimited' || (prod.stock_tecnico ?? 0) > 0;
|
return this.selectedVariantMax() !== 0;
|
||||||
});
|
});
|
||||||
protected readonly descriptionExpanded = signal(false);
|
protected readonly descriptionExpanded = signal(false);
|
||||||
protected readonly descriptionMaxHeight = signal(0);
|
protected readonly descriptionMaxHeight = signal(0);
|
||||||
@@ -333,14 +329,18 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
this.toastService.danger('No se pudo iniciar la compra directa.');
|
const message =
|
||||||
|
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
||||||
|
? error.error.message
|
||||||
|
: 'No se pudo iniciar la compra directa.';
|
||||||
|
this.toastService.danger(message);
|
||||||
} finally {
|
} finally {
|
||||||
this.creatingDirectPurchase.set(false);
|
this.creatingDirectPurchase.set(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private isVariantAvailable(variant: CatalogItemVariant, product: CatalogItemDetail): boolean {
|
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
||||||
return product.inventory_policy === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
|
return variant.maximum_addable_quantity !== 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected toggleDescription(): void {
|
protected toggleDescription(): void {
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ describe('productDetailResolver', () => {
|
|||||||
has_tickets: false,
|
has_tickets: false,
|
||||||
minimum_use_date: null,
|
minimum_use_date: null,
|
||||||
maximum_use_date: null,
|
maximum_use_date: null,
|
||||||
stock_tecnico: 0,
|
maximum_addable_quantity: 0,
|
||||||
attributes: [],
|
attributes: [],
|
||||||
variants: [],
|
variants: [],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { ActivatedRoute, convertToParamMap, Router } from '@angular/router';
|
import { ActivatedRoute, convertToParamMap, Router } from '@angular/router';
|
||||||
|
|
||||||
import { CheckoutService, PurchaseDetailResponse } from '../../../../core/services/checkout.service';
|
import {
|
||||||
|
CheckoutService,
|
||||||
|
PurchaseDetailResponse,
|
||||||
|
} from '../../../../core/services/checkout.service';
|
||||||
import { Tenant } from '../../../../core/services/tenant.interface';
|
import { Tenant } from '../../../../core/services/tenant.interface';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { PurchaseStatusPageComponent } from './purchase-status-page.component';
|
import { PurchaseStatusPageComponent } from './purchase-status-page.component';
|
||||||
@@ -130,4 +133,89 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
|
|
||||||
openSpy.mockRestore();
|
openSpy.mockRestore();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('polls every five seconds while the payment is pending and shows the confirmation', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const checkoutService = {
|
||||||
|
getPurchase: vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce({ status: 'pending_payment' } as PurchaseDetailResponse)
|
||||||
|
.mockResolvedValueOnce(purchase(true)),
|
||||||
|
withCustomLoading() {
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [PurchaseStatusPageComponent],
|
||||||
|
providers: [
|
||||||
|
{ provide: CheckoutService, useValue: checkoutService },
|
||||||
|
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||||
|
{
|
||||||
|
provide: ActivatedRoute,
|
||||||
|
useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } },
|
||||||
|
},
|
||||||
|
{ provide: Router, useValue: { navigate: vi.fn(), navigateByUrl: vi.fn() } },
|
||||||
|
],
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(PurchaseStatusPageComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
await Promise.resolve();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('ESTAMOS VERIFICANDO TU PAGO');
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(5_000);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!');
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(10_000);
|
||||||
|
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
||||||
|
} finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops polling when the page is destroyed', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const checkoutService = {
|
||||||
|
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||||
|
withCustomLoading() {
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [PurchaseStatusPageComponent],
|
||||||
|
providers: [
|
||||||
|
{ provide: CheckoutService, useValue: checkoutService },
|
||||||
|
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||||
|
{
|
||||||
|
provide: ActivatedRoute,
|
||||||
|
useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } },
|
||||||
|
},
|
||||||
|
{ provide: Router, useValue: { navigate: vi.fn(), navigateByUrl: vi.fn() } },
|
||||||
|
],
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(PurchaseStatusPageComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
await Promise.resolve();
|
||||||
|
fixture.destroy();
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(5_000);
|
||||||
|
|
||||||
|
expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
|
||||||
|
} finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,29 +1,47 @@
|
|||||||
import { ChangeDetectionStrategy, Component, OnInit, computed, inject, signal } from '@angular/core';
|
import {
|
||||||
|
ChangeDetectionStrategy,
|
||||||
|
Component,
|
||||||
|
OnDestroy,
|
||||||
|
OnInit,
|
||||||
|
PLATFORM_ID,
|
||||||
|
computed,
|
||||||
|
inject,
|
||||||
|
signal,
|
||||||
|
} from '@angular/core';
|
||||||
|
import { isPlatformBrowser } from '@angular/common';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
|
|
||||||
import { CheckoutService, PurchaseStatusResponse } from '../../../../core/services/checkout.service';
|
import {
|
||||||
|
CheckoutService,
|
||||||
|
PurchaseStatusResponse,
|
||||||
|
} from '../../../../core/services/checkout.service';
|
||||||
import { findMenu } from '../../../../core/services/menu.utils';
|
import { findMenu } from '../../../../core/services/menu.utils';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||||
|
|
||||||
type PurchaseStatusView = 'approved' | 'pending' | 'rejected' | 'expired' | 'error';
|
type PurchaseStatusView = 'approved' | 'pending' | 'rejected' | 'expired' | 'error';
|
||||||
|
|
||||||
|
const PAYMENT_STATUS_POLL_INTERVAL_MS = 5_000;
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-purchase-status-page',
|
selector: 'app-purchase-status-page',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [ButtonComponent],
|
imports: [ButtonComponent],
|
||||||
templateUrl: './purchase-status-page.component.html',
|
templateUrl: './purchase-status-page.component.html',
|
||||||
styleUrl: './purchase-status-page.component.scss',
|
styleUrl: './purchase-status-page.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
})
|
})
|
||||||
export class PurchaseStatusPageComponent implements OnInit {
|
export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
||||||
private readonly route = inject(ActivatedRoute);
|
private readonly route = inject(ActivatedRoute);
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
|
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
|
||||||
|
|
||||||
private purchaseId: string | null = null;
|
private purchaseId: string | null = null;
|
||||||
private tenantCode: string | null = null;
|
private tenantCode: string | null = null;
|
||||||
|
private pollingTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private isDestroyed = false;
|
||||||
|
|
||||||
protected readonly isLoading = signal(true);
|
protected readonly isLoading = signal(true);
|
||||||
protected readonly status = signal<PurchaseStatusView>('pending');
|
protected readonly status = signal<PurchaseStatusView>('pending');
|
||||||
@@ -57,7 +75,12 @@ export class PurchaseStatusPageComponent implements OnInit {
|
|||||||
void this.loadStatus();
|
void this.loadStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
private async loadStatus(): Promise<void> {
|
ngOnDestroy(): void {
|
||||||
|
this.isDestroyed = true;
|
||||||
|
this.stopPolling();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadStatus(isPolling = false): Promise<void> {
|
||||||
if (!this.purchaseId || !this.tenantCode) {
|
if (!this.purchaseId || !this.tenantCode) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -66,13 +89,52 @@ export class PurchaseStatusPageComponent implements OnInit {
|
|||||||
const purchase = await this.checkoutService
|
const purchase = await this.checkoutService
|
||||||
.withCustomLoading()
|
.withCustomLoading()
|
||||||
.getPurchase(this.tenantCode, this.purchaseId);
|
.getPurchase(this.tenantCode, this.purchaseId);
|
||||||
this.status.set(this.resolveStatus(purchase));
|
|
||||||
|
if (this.isDestroyed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const status = this.resolveStatus(purchase);
|
||||||
|
this.status.set(status);
|
||||||
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
|
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
|
||||||
|
|
||||||
|
if (status === 'pending') {
|
||||||
|
this.schedulePolling();
|
||||||
|
} else {
|
||||||
|
this.stopPolling();
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to fetch purchase status:', error);
|
console.error('Failed to fetch purchase status:', error);
|
||||||
this.status.set('error');
|
|
||||||
|
if (!this.isDestroyed) {
|
||||||
|
if (isPolling) {
|
||||||
|
this.schedulePolling();
|
||||||
|
} else {
|
||||||
|
this.status.set('error');
|
||||||
|
}
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
this.isLoading.set(false);
|
if (!this.isDestroyed) {
|
||||||
|
this.isLoading.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private schedulePolling(): void {
|
||||||
|
if (!this.isBrowser || this.isDestroyed || this.pollingTimeout) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.pollingTimeout = setTimeout(() => {
|
||||||
|
this.pollingTimeout = null;
|
||||||
|
void this.loadStatus(true);
|
||||||
|
}, PAYMENT_STATUS_POLL_INTERVAL_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
private stopPolling(): void {
|
||||||
|
if (this.pollingTimeout) {
|
||||||
|
clearTimeout(this.pollingTimeout);
|
||||||
|
this.pollingTimeout = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
[layout]="productLayout()"
|
[layout]="productLayout()"
|
||||||
[groupLayout]="groupLayout()"
|
[groupLayout]="groupLayout()"
|
||||||
[items]="displayItems()"
|
[items]="displayItems()"
|
||||||
|
[savingProductIds]="savingProductIds()"
|
||||||
(buy)="onBuyProduct($event)"
|
(buy)="onBuyProduct($event)"
|
||||||
(addToCart)="onAddToCart($event)"
|
(addToCart)="onAddToCart($event)"
|
||||||
(pageChange)="onPageChange($event)"
|
(pageChange)="onPageChange($event)"
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
signal,
|
signal,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
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 { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
|
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
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 results = signal<ApiPaginatedResponse<CatalogFeaturedItem[]> | null>(null);
|
||||||
protected readonly error = signal<string | null>(null);
|
protected readonly error = signal<string | null>(null);
|
||||||
protected readonly creatingDirectPurchase = signal(false);
|
protected readonly creatingDirectPurchase = signal(false);
|
||||||
|
protected readonly savingProductIds = signal<ReadonlySet<number>>(new Set<number>());
|
||||||
|
|
||||||
protected readonly productLayout = computed<CatalogProductLayout>(
|
protected readonly productLayout = computed<CatalogProductLayout>(
|
||||||
() => this.tenantService.tenant()?.search_product_layout ?? 'column_with_image',
|
() => this.tenantService.tenant()?.search_product_layout ?? 'column_with_image',
|
||||||
@@ -145,7 +146,9 @@ export class SearchPageComponent {
|
|||||||
|
|
||||||
if (!this.injector.get(AuthService).user()) {
|
if (!this.injector.get(AuthService).user()) {
|
||||||
await this.router.navigate(['/login'], {
|
await this.router.navigate(['/login'], {
|
||||||
queryParams: { returnUrl: `/producto/${event.product.id}` },
|
queryParams: {
|
||||||
|
returnUrl: event.reservedInCart ? this.router.url : `/producto/${event.product.id}`,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -158,15 +161,25 @@ export class SearchPageComponent {
|
|||||||
|
|
||||||
this.creatingDirectPurchase.set(true);
|
this.creatingDirectPurchase.set(true);
|
||||||
try {
|
try {
|
||||||
const purchase = await this.injector.get(CheckoutService).startCheckout(tenant.codigo, {
|
const reservedCartId = event.reservedInCart ? (this.cartService.cart()?.id ?? null) : null;
|
||||||
direct_items: [
|
if (event.reservedInCart && reservedCartId === null) {
|
||||||
{
|
this.toastService.danger('No se pudo identificar el carrito reservado.');
|
||||||
catalog_item_id: event.product.id,
|
return;
|
||||||
variant_id: event.variant ?? null,
|
}
|
||||||
cantidad: event.quantity,
|
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 } });
|
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
@@ -177,14 +190,31 @@ export class SearchPageComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onAddToCart(event: ProductListCartEvent): void {
|
protected onAddToCart(event: ProductListCartEvent): void {
|
||||||
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).subscribe({
|
const productId = event.product.id;
|
||||||
next: (response) => {
|
if (this.savingProductIds().has(productId)) {
|
||||||
this.toastService.success(response.message || 'Producto agregado al carrito');
|
return;
|
||||||
},
|
}
|
||||||
error: (error: HttpErrorResponse) => {
|
|
||||||
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
|
this.setProductSaving(productId, true);
|
||||||
this.toastService.danger(message);
|
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;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
</p>
|
</p>
|
||||||
} @else {
|
} @else {
|
||||||
@for (group of catalog(); track group.id) {
|
@for (group of catalog(); track group.id) {
|
||||||
<app-store-section [title]="group.title">
|
<app-store-section [attr.id]="group.code" [title]="group.title">
|
||||||
<app-product-list
|
<app-product-list
|
||||||
[layout]="group.layout"
|
[layout]="group.layout"
|
||||||
[groupLayout]="group.group_layout"
|
[groupLayout]="group.group_layout"
|
||||||
@@ -31,6 +31,7 @@
|
|||||||
[loading]="isGroupLoading(group.id)"
|
[loading]="isGroupLoading(group.id)"
|
||||||
[loadImages]="!hasMainCarouselImages() || mainCarouselReady()"
|
[loadImages]="!hasMainCarouselImages() || mainCarouselReady()"
|
||||||
[unavailableVariantIds]="unavailableVariantIds()"
|
[unavailableVariantIds]="unavailableVariantIds()"
|
||||||
|
[savingProductIds]="savingProductIds()"
|
||||||
(buy)="onBuyProduct($event)"
|
(buy)="onBuyProduct($event)"
|
||||||
(addToCart)="onAddToCart($event)"
|
(addToCart)="onAddToCart($event)"
|
||||||
(pageChange)="onPageChange(group.id, $event)"
|
(pageChange)="onPageChange(group.id, $event)"
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ app-store-section + app-store-section {
|
|||||||
margin-top: clamp(3rem, 6vw, 5rem);
|
margin-top: clamp(3rem, 6vw, 5rem);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
app-store-section[id] {
|
||||||
|
scroll-margin-top: 8rem;
|
||||||
|
}
|
||||||
|
|
||||||
:host > .store-home__additional-info:not(:first-child) {
|
:host > .store-home__additional-info:not(:first-child) {
|
||||||
margin-top: clamp(3rem, 6vw, 5rem);
|
margin-top: clamp(3rem, 6vw, 5rem);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ function createCatalog(
|
|||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
id: 7,
|
id: 7,
|
||||||
|
code: 'destacados',
|
||||||
title: 'Destacados',
|
title: 'Destacados',
|
||||||
layout: 'column_with_image',
|
layout: 'column_with_image',
|
||||||
group_layout: 'paginated',
|
group_layout: 'paginated',
|
||||||
@@ -149,6 +150,7 @@ describe('StoreHomePageComponent', () => {
|
|||||||
const element = fixture.nativeElement as HTMLElement;
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
|
||||||
expect(catalogServiceStub.getCatalog).not.toHaveBeenCalled();
|
expect(catalogServiceStub.getCatalog).not.toHaveBeenCalled();
|
||||||
|
expect(element.querySelector('app-store-section')?.id).toBe('destacados');
|
||||||
expect(element.querySelector('.store-section__title')?.textContent?.trim()).toBe('Destacados');
|
expect(element.querySelector('.store-section__title')?.textContent?.trim()).toBe('Destacados');
|
||||||
expect(element.querySelectorAll('app-product-column-with-image')).toHaveLength(2);
|
expect(element.querySelectorAll('app-product-column-with-image')).toHaveLength(2);
|
||||||
expect(element.textContent).toContain('Auriculares Bluetooth');
|
expect(element.textContent).toContain('Auriculares Bluetooth');
|
||||||
@@ -254,9 +256,10 @@ describe('StoreHomePageComponent', () => {
|
|||||||
const hero = (fixture.nativeElement as HTMLElement).querySelector(
|
const hero = (fixture.nativeElement as HTMLElement).querySelector(
|
||||||
'app-hero-banner .hero-banner',
|
'app-hero-banner .hero-banner',
|
||||||
) as HTMLElement;
|
) as HTMLElement;
|
||||||
|
const heroImage = hero.querySelector('img');
|
||||||
|
|
||||||
expect(hero).not.toBeNull();
|
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('Fiesta Fútbol Infantil');
|
||||||
expect(hero.textContent).toContain('Viví una jornada inolvidable de fútbol infantil.');
|
expect(hero.textContent).toContain('Viví una jornada inolvidable de fútbol infantil.');
|
||||||
expect(hero.textContent).toContain('Rosario, Santa Fe');
|
expect(hero.textContent).toContain('Rosario, Santa Fe');
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import {
|
|||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { Subscription } from 'rxjs';
|
import { finalize, Subscription } from 'rxjs';
|
||||||
|
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
@@ -64,6 +64,7 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly mainCarouselReady = signal(false);
|
protected readonly mainCarouselReady = signal(false);
|
||||||
protected readonly creatingDirectPurchase = signal(false);
|
protected readonly creatingDirectPurchase = signal(false);
|
||||||
protected readonly unavailableVariantIds = signal<ReadonlySet<number>>(new Set<number>());
|
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 mainCarouselImages = computed(() => this.tenant()?.extras?.carousel ?? []);
|
||||||
protected readonly heroConfig = computed(() => this.tenant()?.extras?.heroConfig ?? null);
|
protected readonly heroConfig = computed(() => this.tenant()?.extras?.heroConfig ?? null);
|
||||||
protected readonly additionalInfo = computed(
|
protected readonly additionalInfo = computed(
|
||||||
@@ -169,7 +170,9 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
if (!this.injector.get(AuthService).user()) {
|
if (!this.injector.get(AuthService).user()) {
|
||||||
await this.router.navigate(['/login'], {
|
await this.router.navigate(['/login'], {
|
||||||
queryParams: { returnUrl: `/producto/${event.product.id}` },
|
queryParams: {
|
||||||
|
returnUrl: event.reservedInCart ? this.router.url : `/producto/${event.product.id}`,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -183,6 +186,11 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
|||||||
this.creatingDirectPurchase.set(true);
|
this.creatingDirectPurchase.set(true);
|
||||||
try {
|
try {
|
||||||
const checkoutService = this.injector.get(CheckoutService);
|
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 variantIds = event.variantIds ?? [];
|
||||||
const directItems =
|
const directItems =
|
||||||
variantIds.length > 0
|
variantIds.length > 0
|
||||||
@@ -198,9 +206,10 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
|||||||
cantidad: event.quantity,
|
cantidad: event.quantity,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
const purchase = await checkoutService.startCheckout(tenant.codigo, {
|
const purchase = await checkoutService.startCheckout(
|
||||||
direct_items: directItems,
|
tenant.codigo,
|
||||||
});
|
reservedCartId !== null ? { cart_id: reservedCartId } : { direct_items: directItems },
|
||||||
|
);
|
||||||
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
@@ -215,6 +224,11 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (error instanceof HttpErrorResponse && typeof error.error?.message === 'string') {
|
||||||
|
this.toastService.danger(error.error.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.toastService.danger('No se pudo iniciar la compra directa.');
|
this.toastService.danger('No se pudo iniciar la compra directa.');
|
||||||
} finally {
|
} finally {
|
||||||
this.creatingDirectPurchase.set(false);
|
this.creatingDirectPurchase.set(false);
|
||||||
@@ -222,14 +236,31 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onAddToCart(event: ProductListCartEvent): void {
|
protected onAddToCart(event: ProductListCartEvent): void {
|
||||||
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).subscribe({
|
const productId = event.product.id;
|
||||||
next: (response) => {
|
if (this.savingProductIds().has(productId)) {
|
||||||
this.toastService.success(response.message || 'Producto agregado al carrito');
|
return;
|
||||||
},
|
}
|
||||||
error: (error: HttpErrorResponse) => {
|
|
||||||
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
|
this.setProductSaving(productId, true);
|
||||||
this.toastService.danger(message);
|
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;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (hasVariantSelectors() && !quantityDisabled()) {
|
@if (hasVariantSelectors() && !variantDisabled()) {
|
||||||
<app-variant-selector
|
<app-variant-selector
|
||||||
class="cart-item-variant-selector"
|
class="cart-item-variant-selector"
|
||||||
[variants]="variants()"
|
[variants]="variants()"
|
||||||
@@ -55,7 +55,7 @@
|
|||||||
(increase)="onIncrease()"
|
(increase)="onIncrease()"
|
||||||
(decrease)="onDecrease()"
|
(decrease)="onDecrease()"
|
||||||
/>
|
/>
|
||||||
@if (!quantityDisabled() && showRemove()) {
|
@if (!removeDisabled() && allowDelete()) {
|
||||||
<app-icon-button variant="trash" class="cart-item-remove-btn" (click)="onRemove()" />
|
<app-icon-button variant="trash" class="cart-item-remove-btn" (click)="onRemove()" />
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -31,7 +31,9 @@ export class CartItemComponent {
|
|||||||
readonly quantity = input<number>(1);
|
readonly quantity = input<number>(1);
|
||||||
readonly readonly = input<boolean>(false);
|
readonly readonly = input<boolean>(false);
|
||||||
readonly quantityDisabled = input<boolean>(false);
|
readonly quantityDisabled = input<boolean>(false);
|
||||||
readonly showRemove = input<boolean>(true);
|
readonly variantDisabled = input<boolean>(false);
|
||||||
|
readonly removeDisabled = input<boolean>(false);
|
||||||
|
readonly allowDelete = input<boolean>(true);
|
||||||
|
|
||||||
readonly quantityChange = output<number>();
|
readonly quantityChange = output<number>();
|
||||||
readonly remove = output<void>();
|
readonly remove = output<void>();
|
||||||
@@ -61,7 +63,7 @@ export class CartItemComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onVariantChange(variant: unknown): void {
|
protected onVariantChange(variant: unknown): void {
|
||||||
if (!this.quantityDisabled() && typeof variant === 'number') {
|
if (!this.variantDisabled() && typeof variant === 'number') {
|
||||||
this.variantChange.emit(variant);
|
this.variantChange.emit(variant);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,17 @@
|
|||||||
<section
|
<section
|
||||||
class="d-flex flex-column h-100 overflow-hidden text-secondary"
|
class="d-flex flex-column overflow-hidden text-secondary cart-shell"
|
||||||
[style.background-color]="backgroundColor()"
|
[style.background-color]="backgroundColor()"
|
||||||
>
|
>
|
||||||
<header class="d-flex align-items-center p-3 justify-content-between bg-transparent cart-header">
|
<header class="d-flex align-items-center p-3 justify-content-between bg-transparent cart-header">
|
||||||
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
|
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
|
||||||
|
|
||||||
<div class="d-flex align-items-center cart-header-actions">
|
<div class="d-flex align-items-center cart-header-actions">
|
||||||
@if (!readonly() && allowEditing() && items().length > 0) {
|
@if (
|
||||||
|
allowModify() &&
|
||||||
|
(!readonly() || showModifyWhenReadonly()) &&
|
||||||
|
requireEditingMode() &&
|
||||||
|
items().length > 0
|
||||||
|
) {
|
||||||
<button
|
<button
|
||||||
class="btn btn-link p-0 border-0 cart-edit-btn"
|
class="btn btn-link p-0 border-0 cart-edit-btn"
|
||||||
type="button"
|
type="button"
|
||||||
@@ -48,8 +53,22 @@
|
|||||||
[selectedVariant]="getItemVariant(item)"
|
[selectedVariant]="getItemVariant(item)"
|
||||||
[quantity]="getItemQuantity(item)"
|
[quantity]="getItemQuantity(item)"
|
||||||
[readonly]="readonly()"
|
[readonly]="readonly()"
|
||||||
[quantityDisabled]="editingDisabled() || (allowEditing() && !editing())"
|
[quantityDisabled]="
|
||||||
[showRemove]="allowRemove()"
|
readonly() ||
|
||||||
|
!allowUpdateQuantity() ||
|
||||||
|
editingDisabled() ||
|
||||||
|
(requireEditingMode() && !editing())
|
||||||
|
"
|
||||||
|
[variantDisabled]="
|
||||||
|
readonly() ||
|
||||||
|
!allowUpdateVariant() ||
|
||||||
|
editingDisabled() ||
|
||||||
|
(requireEditingMode() && !editing())
|
||||||
|
"
|
||||||
|
[removeDisabled]="
|
||||||
|
readonly() || !allowDelete() || editingDisabled() || (requireEditingMode() && !editing())
|
||||||
|
"
|
||||||
|
[allowDelete]="allowDelete()"
|
||||||
(quantityChange)="onItemQuantityChange(idx, $event)"
|
(quantityChange)="onItemQuantityChange(idx, $event)"
|
||||||
(variantChange)="onItemVariantChange(idx, $event)"
|
(variantChange)="onItemVariantChange(idx, $event)"
|
||||||
(remove)="onItemRemove(idx)"
|
(remove)="onItemRemove(idx)"
|
||||||
|
|||||||
@@ -1,7 +1,15 @@
|
|||||||
:host {
|
:host {
|
||||||
display: block;
|
display: flex;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
min-height: 0;
|
||||||
|
max-height: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-shell {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-height: 0;
|
||||||
|
max-height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.cart-header {
|
.cart-header {
|
||||||
|
|||||||
@@ -340,7 +340,7 @@ describe('CartComponent', () => {
|
|||||||
quantity: 1,
|
quantity: 1,
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
fixture.componentRef.setInput('allowEditing', true);
|
fixture.componentRef.setInput('requireEditingMode', true);
|
||||||
const editingChange = vi.fn();
|
const editingChange = vi.fn();
|
||||||
fixture.componentInstance.editing.subscribe(editingChange);
|
fixture.componentInstance.editing.subscribe(editingChange);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -408,6 +408,55 @@ describe('CartComponent', () => {
|
|||||||
).toBe(false);
|
).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('hides the edit toggle and disables quantity changes when quantity updates are 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('requireEditingMode', true);
|
||||||
|
fixture.componentRef.setInput('allowModify', false);
|
||||||
|
fixture.componentRef.setInput('allowUpdateQuantity', 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 () => {
|
it('persists a variant selected from a cart row', async () => {
|
||||||
const updateItemVariant = vi.fn().mockReturnValue(
|
const updateItemVariant = vi.fn().mockReturnValue(
|
||||||
of({
|
of({
|
||||||
|
|||||||
@@ -53,9 +53,15 @@ export class CartComponent {
|
|||||||
readonly total = input<number>(0);
|
readonly total = input<number>(0);
|
||||||
readonly backgroundColor = input<string>('#ffffff');
|
readonly backgroundColor = input<string>('#ffffff');
|
||||||
readonly readonly = input<boolean>(false);
|
readonly readonly = input<boolean>(false);
|
||||||
readonly allowEditing = input<boolean>(false);
|
readonly allowUpdateQuantity = input<boolean>(true);
|
||||||
readonly allowRemove = input<boolean>(true);
|
readonly allowModify = input<boolean>(true);
|
||||||
|
readonly showModifyWhenReadonly = input<boolean>(false);
|
||||||
|
readonly requireEditingMode = input<boolean>(false);
|
||||||
|
readonly allowUpdateVariant = input<boolean>(true);
|
||||||
|
readonly allowDelete = input<boolean>(true);
|
||||||
readonly persistQuantityChanges = input<boolean>(true);
|
readonly persistQuantityChanges = input<boolean>(true);
|
||||||
|
readonly persistVariantChanges = input<boolean>(true);
|
||||||
|
readonly persistDeleteChanges = input<boolean>(true);
|
||||||
readonly editingDisabled = input<boolean>(false);
|
readonly editingDisabled = input<boolean>(false);
|
||||||
readonly editing = model<boolean>(false);
|
readonly editing = model<boolean>(false);
|
||||||
|
|
||||||
@@ -65,6 +71,12 @@ export class CartComponent {
|
|||||||
index: number;
|
index: number;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
}>();
|
}>();
|
||||||
|
readonly itemVariantChange = output<{
|
||||||
|
item: CartItemMock;
|
||||||
|
index: number;
|
||||||
|
variantId: number;
|
||||||
|
}>();
|
||||||
|
readonly itemRemove = output<{ item: CartItemMock; index: number }>();
|
||||||
|
|
||||||
protected readonly quantityOverrides = signal<Record<number, number>>({});
|
protected readonly quantityOverrides = signal<Record<number, number>>({});
|
||||||
protected readonly variantOverrides = signal<Record<number, number>>({});
|
protected readonly variantOverrides = signal<Record<number, number>>({});
|
||||||
@@ -124,6 +136,10 @@ export class CartComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onItemQuantityChange(index: number, newQuantity: number): void {
|
protected onItemQuantityChange(index: number, newQuantity: number): void {
|
||||||
|
if (!this.allowUpdateQuantity()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const mockItem = this.items()[index];
|
const mockItem = this.items()[index];
|
||||||
if (!mockItem) {
|
if (!mockItem) {
|
||||||
return;
|
return;
|
||||||
@@ -165,11 +181,19 @@ export class CartComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onItemVariantChange(index: number, variantId: number): void {
|
protected onItemVariantChange(index: number, variantId: number): void {
|
||||||
|
if (this.readonly() || !this.allowUpdateVariant() || this.editingDisabled()) return;
|
||||||
|
|
||||||
const item = this.items()[index];
|
const item = this.items()[index];
|
||||||
const cartItemId = item?.cartItemId;
|
const cartItemId = item?.cartItemId;
|
||||||
|
|
||||||
if (!item || !cartItemId || variantId === this.getItemVariant(item)) return;
|
if (!item || !cartItemId || variantId === this.getItemVariant(item)) return;
|
||||||
|
|
||||||
|
this.itemVariantChange.emit({ item, index, variantId });
|
||||||
|
|
||||||
|
if (!this.persistVariantChanges()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.variantOverrides.update((overrides) => ({ ...overrides, [cartItemId]: variantId }));
|
this.variantOverrides.update((overrides) => ({ ...overrides, [cartItemId]: variantId }));
|
||||||
this.cartService
|
this.cartService
|
||||||
.updateItemVariant(cartItemId, this.getItemQuantity(item), variantId)
|
.updateItemVariant(cartItemId, this.getItemQuantity(item), variantId)
|
||||||
@@ -195,6 +219,8 @@ export class CartComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onItemRemove(index: number): void {
|
protected onItemRemove(index: number): void {
|
||||||
|
if (this.readonly() || !this.allowDelete() || this.editingDisabled()) return;
|
||||||
|
|
||||||
const target = this.resolveRemoveTarget(index);
|
const target = this.resolveRemoveTarget(index);
|
||||||
|
|
||||||
if (!target) {
|
if (!target) {
|
||||||
@@ -210,7 +236,14 @@ export class CartComponent {
|
|||||||
})
|
})
|
||||||
.subscribe((confirmed) => {
|
.subscribe((confirmed) => {
|
||||||
if (confirmed) {
|
if (confirmed) {
|
||||||
this.removeItem(target.cartItemId);
|
const item = this.items()[index];
|
||||||
|
if (item) {
|
||||||
|
this.itemRemove.emit({ item, index });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.persistDeleteChanges()) {
|
||||||
|
this.removeItem(target.cartItemId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -220,7 +253,7 @@ export class CartComponent {
|
|||||||
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
|
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
|
||||||
|
|
||||||
protected toggleEditing(): void {
|
protected toggleEditing(): void {
|
||||||
if (this.editingDisabled()) {
|
if (!this.allowModify() || this.editingDisabled()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,7 +287,7 @@ export class CartComponent {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
cartItemId: item.id,
|
cartItemId: item.id,
|
||||||
productName: item.product?.nombre ?? 'este producto',
|
productName: item.nombre ?? 'este producto',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
<div class="hero-banner-container">
|
<div class="hero-banner-container">
|
||||||
<div class="hero-banner position-relative rounded">
|
<div class="hero-banner position-relative rounded">
|
||||||
<div
|
@if (desktopImageUrl) {
|
||||||
class="hero-media"
|
<picture class="hero-media" aria-hidden="true">
|
||||||
aria-hidden="true"
|
@if (mobileImageUrl) {
|
||||||
[ngStyle]="{
|
<source media="(max-width: 767.98px)" [srcset]="mobileImageUrl" />
|
||||||
'background-image': heroConfig?.background_image_id
|
}
|
||||||
? 'url(' + heroConfig.background_image_id + ')'
|
<img [src]="desktopImageUrl" alt="" />
|
||||||
: 'none',
|
</picture>
|
||||||
}"
|
}
|
||||||
></div>
|
|
||||||
|
|
||||||
@if (heroConfig) {
|
@if (heroConfig) {
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -12,11 +12,20 @@
|
|||||||
.hero-media {
|
.hero-media {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
|
display: block;
|
||||||
|
overflow: hidden;
|
||||||
background-position: center;
|
background-position: center;
|
||||||
background-repeat: no-repeat;
|
background-repeat: no-repeat;
|
||||||
background-size: cover;
|
background-size: cover;
|
||||||
border-radius: inherit;
|
border-radius: inherit;
|
||||||
|
|
||||||
|
img {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
|
||||||
&::after {
|
&::after {
|
||||||
content: '';
|
content: '';
|
||||||
position: absolute;
|
position: absolute;
|
||||||
|
|||||||
@@ -2,6 +2,28 @@ import { TestBed } from '@angular/core/testing';
|
|||||||
import { HeroBannerComponent } from './hero-banner.component';
|
import { HeroBannerComponent } from './hero-banner.component';
|
||||||
|
|
||||||
describe('HeroBannerComponent', () => {
|
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 () => {
|
it('expands and collapses the event schedules', async () => {
|
||||||
await TestBed.configureTestingModule({ imports: [HeroBannerComponent] }).compileComponents();
|
await TestBed.configureTestingModule({ imports: [HeroBannerComponent] }).compileComponents();
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,18 @@ export class HeroBannerComponent {
|
|||||||
|
|
||||||
protected schedulesExpanded = false;
|
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 {
|
get formattedDates(): string {
|
||||||
if (this.eventConfig?.dates_text) {
|
if (this.eventConfig?.dates_text) {
|
||||||
return this.eventConfig.dates_text;
|
return this.eventConfig.dates_text;
|
||||||
|
|||||||
@@ -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)
|
// Hover/Active/Focus colors (non-disabled)
|
||||||
.icon-btn:hover:not(:disabled),
|
.icon-btn:hover:not(:disabled),
|
||||||
.icon-btn:focus-visible:not(:disabled),
|
.icon-btn:focus-visible:not(:disabled),
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ export type IconButtonVariant =
|
|||||||
})
|
})
|
||||||
export class IconButtonComponent {
|
export class IconButtonComponent {
|
||||||
readonly variant = input.required<IconButtonVariant>();
|
readonly variant = input.required<IconButtonVariant>();
|
||||||
|
readonly bordered = input(false);
|
||||||
readonly disabled = input(false);
|
readonly disabled = input(false);
|
||||||
readonly ariaLabel = input<string>('');
|
readonly ariaLabel = input<string>('');
|
||||||
readonly ariaExpanded = input<boolean | null>(null);
|
readonly ariaExpanded = input<boolean | null>(null);
|
||||||
@@ -45,6 +46,10 @@ export class IconButtonComponent {
|
|||||||
});
|
});
|
||||||
|
|
||||||
protected readonly buttonClasses = computed(() => {
|
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(),
|
||||||
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,9 @@
|
|||||||
[title]="item.nombre"
|
[title]="item.nombre"
|
||||||
[description]="item.descripcion ?? ''"
|
[description]="item.descripcion ?? ''"
|
||||||
[price]="price(item)"
|
[price]="price(item)"
|
||||||
|
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
|
||||||
[variants]="item.variants ?? []"
|
[variants]="item.variants ?? []"
|
||||||
|
[saving]="savingProductIds().has(item.id)"
|
||||||
(buy)="emitRowBuy(item, $event)"
|
(buy)="emitRowBuy(item, $event)"
|
||||||
(addToCart)="emitRowCart(item, $event)"
|
(addToCart)="emitRowCart(item, $event)"
|
||||||
/>
|
/>
|
||||||
@@ -22,19 +24,20 @@
|
|||||||
[title]="item.nombre"
|
[title]="item.nombre"
|
||||||
[description]="item.descripcion ?? ''"
|
[description]="item.descripcion ?? ''"
|
||||||
[price]="price(item)"
|
[price]="price(item)"
|
||||||
|
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
|
||||||
[variants]="item.variants ?? []"
|
[variants]="item.variants ?? []"
|
||||||
|
[saving]="savingProductIds().has(item.id)"
|
||||||
(buy)="emitColumnBuy(item, $event)"
|
(buy)="emitColumnBuy(item, $event)"
|
||||||
(addToCart)="emitColumnCart(item, $event)"
|
(addToCart)="emitColumnCart(item, $event)"
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
@case ('ticket_selector') {
|
@case ('ticket_selector') {
|
||||||
<app-product-ticket-selector
|
<app-product-ticket-selector
|
||||||
|
[productId]="item.id"
|
||||||
[title]="item.nombre"
|
[title]="item.nombre"
|
||||||
[description]="item.descripcion ?? ''"
|
[description]="item.descripcion ?? ''"
|
||||||
[price]="price(item)"
|
[price]="price(item)"
|
||||||
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
||||||
[variants]="item.variants ?? []"
|
|
||||||
[unavailableVariantIds]="unavailableVariantIds()"
|
|
||||||
[disabled]="loading()"
|
[disabled]="loading()"
|
||||||
(buy)="emitTicketBuy(item, $event)"
|
(buy)="emitTicketBuy(item, $event)"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||||
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { of } from 'rxjs';
|
||||||
|
|
||||||
import { ApiPaginatedResponse } from '../../../core/services/api-paginated-response.interface';
|
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 {
|
import {
|
||||||
CatalogFeaturedItems,
|
CatalogFeaturedItems,
|
||||||
CatalogGroupLayout,
|
CatalogGroupLayout,
|
||||||
@@ -51,7 +54,29 @@ describe('ProductListComponent', () => {
|
|||||||
productItems: CatalogFeaturedItems = paginatedItems(),
|
productItems: CatalogFeaturedItems = paginatedItems(),
|
||||||
groupLayout: CatalogGroupLayout = 'paginated',
|
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);
|
const fixture = TestBed.createComponent(ProductListComponent);
|
||||||
fixture.componentRef.setInput('layout', layout);
|
fixture.componentRef.setInput('layout', layout);
|
||||||
fixture.componentRef.setInput('groupLayout', groupLayout);
|
fixture.componentRef.setInput('groupLayout', groupLayout);
|
||||||
@@ -168,8 +193,8 @@ describe('ProductListComponent', () => {
|
|||||||
const itemWithVariants: ProductListItem = {
|
const itemWithVariants: ProductListItem = {
|
||||||
...items[0],
|
...items[0],
|
||||||
variants: [
|
variants: [
|
||||||
{ id: 91, stock_tecnico: 3, values: { fecha: '10 de octubre' } },
|
{ id: 91, maximum_addable_quantity: 3, values: { fecha: '10 de octubre' } },
|
||||||
{ id: 92, stock_tecnico: 4, values: { fecha: '11 de octubre' } },
|
{ id: 92, maximum_addable_quantity: 4, values: { fecha: '11 de octubre' } },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
const fixture = await render('column_with_cart', [itemWithVariants]);
|
const fixture = await render('column_with_cart', [itemWithVariants]);
|
||||||
@@ -189,6 +214,58 @@ describe('ProductListComponent', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('caps the quantity at the selected variant maximum', async () => {
|
||||||
|
const itemWithVariants: ProductListItem = {
|
||||||
|
...items[0],
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
id: 91,
|
||||||
|
maximum_addable_quantity: 2,
|
||||||
|
values: { fecha: '10 de octubre' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const fixture = await render('column_with_cart', [itemWithVariants]);
|
||||||
|
await fixture.whenStable();
|
||||||
|
fixture.detectChanges();
|
||||||
|
const increase = fixture.nativeElement.querySelector(
|
||||||
|
'.quantity-selector__button:last-child',
|
||||||
|
) as HTMLButtonElement;
|
||||||
|
|
||||||
|
increase.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
(fixture.nativeElement as HTMLElement).querySelector('.quantity-selector__value')
|
||||||
|
?.textContent,
|
||||||
|
).toContain('2');
|
||||||
|
expect(increase.disabled).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('disables purchase actions when the selected variant maximum is zero', async () => {
|
||||||
|
const unavailableItem: ProductListItem = {
|
||||||
|
...items[0],
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
id: 91,
|
||||||
|
maximum_addable_quantity: 0,
|
||||||
|
values: { fecha: '10 de octubre' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const fixture = await render('row', [unavailableItem]);
|
||||||
|
await fixture.whenStable();
|
||||||
|
fixture.detectChanges();
|
||||||
|
const buttons = Array.from(
|
||||||
|
(fixture.nativeElement as HTMLElement).querySelectorAll<HTMLButtonElement>(
|
||||||
|
'.product-row-card__buttons button',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(buttons).toHaveLength(2);
|
||||||
|
expect(buttons.every((button) => button.disabled)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
it('renders pagination and emits the requested page', async () => {
|
it('renders pagination and emits the requested page', async () => {
|
||||||
const fixture = await render('row');
|
const fixture = await render('row');
|
||||||
const pageChangeSpy = vi.fn();
|
const pageChangeSpy = vi.fn();
|
||||||
@@ -227,7 +304,7 @@ describe('ProductListComponent', () => {
|
|||||||
{
|
{
|
||||||
id: 401,
|
id: 401,
|
||||||
precio: '10000.00',
|
precio: '10000.00',
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: { value: 'vip', label: 'VIP' },
|
tipo: { value: 'vip', label: 'VIP' },
|
||||||
sector: { value: 'a', label: 'Sector A' },
|
sector: { value: 'a', label: 'Sector A' },
|
||||||
@@ -238,7 +315,7 @@ describe('ProductListComponent', () => {
|
|||||||
{
|
{
|
||||||
id: 402,
|
id: 402,
|
||||||
precio: '12000.00',
|
precio: '12000.00',
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: { value: 'vip', label: 'VIP' },
|
tipo: { value: 'vip', label: 'VIP' },
|
||||||
sector: { value: 'a', label: 'Sector A' },
|
sector: { value: 'a', label: 'Sector A' },
|
||||||
@@ -265,7 +342,12 @@ describe('ProductListComponent', () => {
|
|||||||
|
|
||||||
const ticketSelector = fixture.debugElement.query(By.directive(ProductTicketSelectorComponent))
|
const ticketSelector = fixture.debugElement.query(By.directive(ProductTicketSelectorComponent))
|
||||||
.componentInstance as ProductTicketSelectorComponent;
|
.componentInstance as ProductTicketSelectorComponent;
|
||||||
ticketSelector['updateRow'](1, 401);
|
ticketSelector['patchRow'](1, {
|
||||||
|
variantId: 401,
|
||||||
|
reservedVariantId: 401,
|
||||||
|
cartItemId: 1,
|
||||||
|
status: 'reserved',
|
||||||
|
});
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
(element.querySelector('.ticket-selector__add-row-button') as HTMLButtonElement).click();
|
(element.querySelector('.ticket-selector__add-row-button') as HTMLButtonElement).click();
|
||||||
@@ -274,7 +356,12 @@ describe('ProductListComponent', () => {
|
|||||||
expect(element.querySelectorAll('.ticket-selector__row')).toHaveLength(2);
|
expect(element.querySelectorAll('.ticket-selector__row')).toHaveLength(2);
|
||||||
expect(element.querySelectorAll('.variant-selector__select')).toHaveLength(8);
|
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();
|
fixture.detectChanges();
|
||||||
|
|
||||||
(element.querySelector('.ticket-selector__actions .btn-primary') as HTMLButtonElement).click();
|
(element.querySelector('.ticket-selector__actions .btn-primary') as HTMLButtonElement).click();
|
||||||
@@ -285,26 +372,24 @@ describe('ProductListComponent', () => {
|
|||||||
variant: 401,
|
variant: 401,
|
||||||
variantIds: [401, 402],
|
variantIds: [401, 402],
|
||||||
directPurchase: true,
|
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 = {
|
const ticket: ProductListItem = {
|
||||||
...items[0],
|
...items[0],
|
||||||
variants: [
|
variants: undefined,
|
||||||
{ id: 401, stock_tecnico: 1, values: { asiento: { value: '1', label: '1' } } },
|
|
||||||
{ id: 402, stock_tecnico: 1, values: { asiento: { value: '2', label: '2' } } },
|
|
||||||
],
|
|
||||||
};
|
};
|
||||||
const fixture = await render('ticket_selector', [ticket], 'single');
|
const fixture = await render('ticket_selector', [ticket], 'single');
|
||||||
fixture.componentRef.setInput('unavailableVariantIds', new Set([401]));
|
|
||||||
await fixture.whenStable();
|
await fixture.whenStable();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const selector = fixture.debugElement.query(By.directive(ProductTicketSelectorComponent))
|
const selector = fixture.debugElement.query(By.directive(ProductTicketSelectorComponent))
|
||||||
.componentInstance as 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 () => {
|
it('renders carousel groups with the reusable carousel', async () => {
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ export interface ProductListBuyEvent {
|
|||||||
variant?: number | null;
|
variant?: number | null;
|
||||||
variantIds?: number[];
|
variantIds?: number[];
|
||||||
directPurchase: boolean;
|
directPurchase: boolean;
|
||||||
|
reservedInCart?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -68,6 +69,7 @@ export class ProductListComponent {
|
|||||||
readonly loading = input(false);
|
readonly loading = input(false);
|
||||||
readonly loadImages = input(true);
|
readonly loadImages = input(true);
|
||||||
readonly unavailableVariantIds = input<ReadonlySet<number>>(new Set<number>());
|
readonly unavailableVariantIds = input<ReadonlySet<number>>(new Set<number>());
|
||||||
|
readonly savingProductIds = input<ReadonlySet<number>>(new Set<number>());
|
||||||
|
|
||||||
readonly buy = output<ProductListBuyEvent>();
|
readonly buy = output<ProductListBuyEvent>();
|
||||||
readonly addToCart = output<ProductListCartEvent>();
|
readonly addToCart = output<ProductListCartEvent>();
|
||||||
@@ -159,6 +161,7 @@ export class ProductListComponent {
|
|||||||
variant: variantIds[0] ?? null,
|
variant: variantIds[0] ?? null,
|
||||||
variantIds,
|
variantIds,
|
||||||
directPurchase: true,
|
directPurchase: true,
|
||||||
|
reservedInCart: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,11 @@
|
|||||||
[(selectedVariant)]="selectedVariant"
|
[(selectedVariant)]="selectedVariant"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<app-quantity-selector [(quantity)]="quantity"></app-quantity-selector>
|
<app-quantity-selector
|
||||||
|
[(quantity)]="quantity"
|
||||||
|
[max]="effectiveMaximum()"
|
||||||
|
[disabled]="unavailable()"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="product-row-card__price text-primary">
|
<span class="product-row-card__price text-primary">
|
||||||
@@ -31,10 +35,18 @@
|
|||||||
|
|
||||||
<div class="product-row-card__buttons">
|
<div class="product-row-card__buttons">
|
||||||
<div class="product-row-card__btn-wrapper">
|
<div class="product-row-card__btn-wrapper">
|
||||||
<app-button variant="primary" (click)="onBuy()"> Comprar </app-button>
|
<app-button variant="primary" [disabled]="unavailable()" (click)="onBuy()">
|
||||||
|
Comprar
|
||||||
|
</app-button>
|
||||||
</div>
|
</div>
|
||||||
<div class="product-row-card__btn-wrapper">
|
<div class="product-row-card__btn-wrapper">
|
||||||
<app-button variant="secondary" (click)="onAddToCart()"> Agregar al carrito </app-button>
|
<app-button
|
||||||
|
variant="secondary"
|
||||||
|
[disabled]="saving() || unavailable()"
|
||||||
|
(click)="onAddToCart()"
|
||||||
|
>
|
||||||
|
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}
|
||||||
|
</app-button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,12 @@
|
|||||||
import { ChangeDetectionStrategy, Component, computed, input, model, output } from '@angular/core';
|
import {
|
||||||
|
ChangeDetectionStrategy,
|
||||||
|
Component,
|
||||||
|
computed,
|
||||||
|
effect,
|
||||||
|
input,
|
||||||
|
model,
|
||||||
|
output,
|
||||||
|
} from '@angular/core';
|
||||||
import { ButtonComponent } from '../button/button.component';
|
import { ButtonComponent } from '../button/button.component';
|
||||||
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
||||||
import {
|
import {
|
||||||
@@ -10,7 +18,7 @@ export interface Variant extends VariantSelectorVariant {
|
|||||||
label?: string;
|
label?: string;
|
||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string | number;
|
precio?: string | number;
|
||||||
stock_tecnico?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -26,7 +34,9 @@ export class ProductRowCardComponent {
|
|||||||
readonly title = input<string>('');
|
readonly title = input<string>('');
|
||||||
readonly description = input<string>('');
|
readonly description = input<string>('');
|
||||||
readonly price = input<number>(0);
|
readonly price = input<number>(0);
|
||||||
|
readonly maximumAddableQuantity = input<number | null>(null);
|
||||||
readonly variants = input<Variant[]>([]);
|
readonly variants = input<Variant[]>([]);
|
||||||
|
readonly saving = input(false);
|
||||||
|
|
||||||
// Internal state models
|
// Internal state models
|
||||||
readonly quantity = model<number>(1);
|
readonly quantity = model<number>(1);
|
||||||
@@ -47,10 +57,28 @@ export class ProductRowCardComponent {
|
|||||||
|
|
||||||
return Number.isFinite(variantPrice) ? variantPrice : this.price();
|
return Number.isFinite(variantPrice) ? variantPrice : this.price();
|
||||||
});
|
});
|
||||||
|
protected readonly effectiveMaximum = computed(
|
||||||
|
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
|
||||||
|
);
|
||||||
|
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
|
||||||
|
|
||||||
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
const maximum = this.effectiveMaximum();
|
||||||
|
|
||||||
|
if (maximum !== null && maximum > 0 && this.quantity() > maximum) {
|
||||||
|
this.quantity.set(maximum);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
protected onAddToCart(): void {
|
protected onAddToCart(): void {
|
||||||
|
if (this.saving() || this.unavailable()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.addToCart.emit({
|
this.addToCart.emit({
|
||||||
quantity: this.quantity(),
|
quantity: this.quantity(),
|
||||||
variant: this.selectedVariant(),
|
variant: this.selectedVariant(),
|
||||||
@@ -58,6 +86,8 @@ export class ProductRowCardComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onBuy(): void {
|
protected onBuy(): void {
|
||||||
|
if (this.unavailable()) return;
|
||||||
|
|
||||||
this.buy.emit({
|
this.buy.emit({
|
||||||
quantity: this.quantity(),
|
quantity: this.quantity(),
|
||||||
variant: this.selectedVariant(),
|
variant: this.selectedVariant(),
|
||||||
|
|||||||
@@ -20,20 +20,58 @@
|
|||||||
<span class="ticket-selector__label">Seleccioná Entrada/s:</span>
|
<span class="ticket-selector__label">Seleccioná Entrada/s:</span>
|
||||||
|
|
||||||
<div class="ticket-selector__rows">
|
<div class="ticket-selector__rows">
|
||||||
|
@if (attributes().length > 0) {
|
||||||
|
<div class="ticket-selector__columns" aria-hidden="true">
|
||||||
|
<div class="ticket-selector__column-labels">
|
||||||
|
@for (attribute of attributes(); track attribute.key) {
|
||||||
|
<span class="ticket-selector__column-label">{{ attribute.label }}</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<span class="ticket-selector__action-spacer"></span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
@for (row of rows(); track row.id) {
|
@for (row of rows(); track row.id) {
|
||||||
<div class="ticket-selector__row">
|
<div class="ticket-selector__row">
|
||||||
<app-variant-selector
|
<div class="ticket-selector__row-content">
|
||||||
class="ticket-selector__fields"
|
<div class="ticket-selector__fields variant-selector">
|
||||||
[variants]="variantsForRow(row.id)"
|
@for (selector of row.selectors; track selector.key) {
|
||||||
[disabled]="disabled()"
|
<select
|
||||||
[autoSelectFirst]="false"
|
class="form-select variant-selector__select"
|
||||||
[selectedVariant]="row.variantId"
|
[attr.aria-label]="selector.label"
|
||||||
(selectedVariantChange)="updateRow(row.id, $event)"
|
[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
|
<app-icon-button
|
||||||
variant="trash"
|
variant="trash"
|
||||||
|
[bordered]="true"
|
||||||
ariaLabel="Eliminar entrada"
|
ariaLabel="Eliminar entrada"
|
||||||
[disabled]="disabled()"
|
[disabled]="rowDisabled(row)"
|
||||||
(clicked)="removeRow(row.id)"
|
(clicked)="removeRow(row.id)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -50,7 +88,7 @@
|
|||||||
+ Agregar entrada
|
+ Agregar entrada
|
||||||
</app-button>
|
</app-button>
|
||||||
|
|
||||||
@if (selectableVariants().length === 0) {
|
@if (availableVariantCount() === 0) {
|
||||||
<p class="ticket-selector__empty">No hay entradas disponibles.</p>
|
<p class="ticket-selector__empty">No hay entradas disponibles.</p>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -45,7 +45,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
&__label {
|
&__label {
|
||||||
display: block;
|
display: inline-block;
|
||||||
margin-bottom: 0.5rem;
|
margin-bottom: 0.5rem;
|
||||||
color: #555;
|
color: #555;
|
||||||
font-size: 15px;
|
font-size: 15px;
|
||||||
@@ -57,20 +57,60 @@
|
|||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
&__row {
|
&__columns {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: minmax(0, 1fr) auto;
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
align-items: end;
|
align-items: end;
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
&__column-labels {
|
||||||
|
min-width: 0;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(4, minmax(120px, 1fr));
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__column-label {
|
||||||
|
color: #666;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__action-spacer {
|
||||||
|
width: 38px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
|
align-items: start;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__row-content {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
&__fields {
|
&__fields {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(4, minmax(120px, 1fr));
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
::ng-deep .variant-selector {
|
.variant-selector__select {
|
||||||
display: grid;
|
width: 100%;
|
||||||
grid-template-columns: repeat(4, minmax(120px, 1fr));
|
min-width: 0;
|
||||||
gap: 0.5rem;
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,6 +124,25 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
&__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 {
|
&__empty {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
color: #777;
|
color: #777;
|
||||||
@@ -103,6 +162,18 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@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) {
|
@media (max-width: 767.98px) {
|
||||||
.ticket-selector {
|
.ticket-selector {
|
||||||
&__header {
|
&__header {
|
||||||
@@ -110,9 +181,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
&__fields {
|
&__fields {
|
||||||
::ng-deep .variant-selector {
|
grid-template-columns: 1fr;
|
||||||
grid-template-columns: 1fr;
|
}
|
||||||
}
|
|
||||||
|
&__columns {
|
||||||
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
&__map {
|
&__map {
|
||||||
|
|||||||
@@ -0,0 +1,310 @@
|
|||||||
|
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('shows one header row with the label of every selector', async () => {
|
||||||
|
const { fixture } = await createComponent({
|
||||||
|
maps: [mapResponse([variant(401, 'general', 'A', '1', '1')])],
|
||||||
|
});
|
||||||
|
|
||||||
|
const headerRows = fixture.nativeElement.querySelectorAll('.ticket-selector__columns');
|
||||||
|
const labels = fixture.nativeElement.querySelectorAll('.ticket-selector__column-label');
|
||||||
|
|
||||||
|
expect(headerRows).toHaveLength(1);
|
||||||
|
expect([...labels].map((label: Element) => label.textContent?.trim())).toEqual([
|
||||||
|
'Tipo',
|
||||||
|
'Sector',
|
||||||
|
'Fila',
|
||||||
|
'Asiento',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
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',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,76 +1,120 @@
|
|||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import {
|
import {
|
||||||
|
afterNextRender,
|
||||||
ChangeDetectionStrategy,
|
ChangeDetectionStrategy,
|
||||||
Component,
|
Component,
|
||||||
computed,
|
computed,
|
||||||
|
DestroyRef,
|
||||||
effect,
|
effect,
|
||||||
|
inject,
|
||||||
input,
|
input,
|
||||||
output,
|
output,
|
||||||
signal,
|
signal,
|
||||||
|
untracked,
|
||||||
} from '@angular/core';
|
} 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 { ButtonComponent } from '../button/button.component';
|
||||||
import { IconButtonComponent } from '../icon-button/icon-button.component';
|
import { IconButtonComponent } from '../icon-button/icon-button.component';
|
||||||
import {
|
|
||||||
VariantSelectorComponent,
|
|
||||||
VariantSelectorVariant,
|
|
||||||
} from '../variant-selector/variant-selector.component';
|
|
||||||
|
|
||||||
export interface TicketSelectorVariant extends VariantSelectorVariant {
|
type TicketSelectionStatus =
|
||||||
precio?: string | number;
|
| 'selecting'
|
||||||
stock_tecnico?: number | null;
|
| 'checking'
|
||||||
|
| 'reserving'
|
||||||
|
| 'reserved'
|
||||||
|
| 'removing'
|
||||||
|
| 'error';
|
||||||
|
|
||||||
|
interface VariantAttribute {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TicketSelectionRow {
|
interface TicketSelectionRow {
|
||||||
id: number;
|
id: number;
|
||||||
variantId: number | null;
|
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({
|
@Component({
|
||||||
selector: 'app-product-ticket-selector',
|
selector: 'app-product-ticket-selector',
|
||||||
imports: [ButtonComponent, IconButtonComponent, VariantSelectorComponent],
|
imports: [ButtonComponent, IconButtonComponent],
|
||||||
templateUrl: './product-ticket-selector.component.html',
|
templateUrl: './product-ticket-selector.component.html',
|
||||||
styleUrl: './product-ticket-selector.component.scss',
|
styleUrl: './product-ticket-selector.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
})
|
})
|
||||||
export class ProductTicketSelectorComponent {
|
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[]>([]);
|
||||||
|
protected readonly attributes = signal<VariantAttribute[]>([]);
|
||||||
|
private mapRequest: Subscription | null = null;
|
||||||
|
|
||||||
|
readonly productId = input.required<number>();
|
||||||
readonly title = input.required<string>();
|
readonly title = input.required<string>();
|
||||||
readonly description = input<string>('');
|
readonly description = input<string>('');
|
||||||
readonly price = input<number>(0);
|
readonly price = input<number>(0);
|
||||||
readonly imageUrl = input<string | null>(null);
|
readonly imageUrl = input<string | null>(null);
|
||||||
readonly variants = input<TicketSelectorVariant[]>([]);
|
|
||||||
readonly unavailableVariantIds = input<ReadonlySet<number>>(new Set<number>());
|
|
||||||
readonly disabled = input(false);
|
readonly disabled = input(false);
|
||||||
|
|
||||||
readonly buy = output<number[]>();
|
readonly buy = output<number[]>();
|
||||||
|
|
||||||
protected readonly rows = signal<TicketSelectionRow[]>([{ id: 1, variantId: null }]);
|
protected readonly rows = signal<TicketSelectionRow[]>([this.createRow(1)]);
|
||||||
|
private readonly remotePriceRange = signal<{ minimum: number; maximum: number } | null>(null);
|
||||||
private nextRowId = 2;
|
private nextRowId = 2;
|
||||||
|
|
||||||
protected readonly selectableVariants = computed<TicketSelectorVariant[]>(() =>
|
protected readonly availableVariantCount = computed(() => {
|
||||||
this.variants().filter(
|
const reservedIds = new Set(
|
||||||
(variant) =>
|
this.rows().flatMap(({ reservedVariantId }) =>
|
||||||
!this.unavailableVariantIds().has(variant.id as number) &&
|
reservedVariantId === null ? [] : [reservedVariantId],
|
||||||
(variant.stock_tecnico == null || variant.stock_tecnico > 0),
|
),
|
||||||
),
|
);
|
||||||
);
|
return this.variants().filter(({ id }) => !reservedIds.has(id)).length;
|
||||||
|
});
|
||||||
protected readonly hasSelection = computed(
|
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 canAddRow = computed(
|
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(() => {
|
protected readonly priceRange = computed(() => {
|
||||||
const prices = this.selectableVariants()
|
const range = this.remotePriceRange();
|
||||||
.map((variant) => Number(variant.precio ?? this.price()))
|
const minimum = range?.minimum ?? this.price();
|
||||||
.filter(Number.isFinite);
|
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 {
|
return {
|
||||||
minimum: this.formatCurrency(minimum),
|
minimum: this.formatCurrency(minimum),
|
||||||
maximum: this.formatCurrency(maximum),
|
maximum: this.formatCurrency(maximum),
|
||||||
@@ -80,56 +124,495 @@ export class ProductTicketSelectorComponent {
|
|||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
effect(() => {
|
effect(() => {
|
||||||
const unavailable = this.unavailableVariantIds();
|
const viewReady = this.viewReady();
|
||||||
|
const mapReady = this.mapReady();
|
||||||
|
const cart = this.cartService.cart?.() ?? null;
|
||||||
|
if (!viewReady) return;
|
||||||
|
|
||||||
if (!this.rows().some((row) => row.variantId !== null && unavailable.has(row.variantId))) {
|
untracked(() => {
|
||||||
return;
|
if (!mapReady) {
|
||||||
}
|
this.loadVariantMap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.synchronizeWithCart(cart?.items ?? []);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
this.rows.update((rows) =>
|
afterNextRender(() => this.viewReady.set(true));
|
||||||
rows.map((row) =>
|
this.destroyRef.onDestroy(() => {
|
||||||
row.variantId !== null && unavailable.has(row.variantId)
|
this.mapRequest?.unsubscribe();
|
||||||
? { ...row, variantId: null }
|
this.reservationRequests.forEach((request) => request.unsubscribe());
|
||||||
: row,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected onBuy(): void {
|
protected onBuy(): void {
|
||||||
const variantIds = this.rows().flatMap((row) =>
|
const variantIds = this.rows().flatMap((row) =>
|
||||||
row.variantId === null ? [] : [row.variantId],
|
row.reservedVariantId === null ? [] : [row.reservedVariantId],
|
||||||
);
|
);
|
||||||
|
if (this.hasSelection() && variantIds.length > 0) this.buy.emit(variantIds);
|
||||||
if (variantIds.length === this.rows().length && variantIds.length > 0) {
|
|
||||||
this.buy.emit(variantIds);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected addRow(): void {
|
protected addRow(): void {
|
||||||
if (!this.canAddRow()) return;
|
if (!this.canAddRow()) return;
|
||||||
this.rows.update((rows) => [...rows, { id: this.nextRowId++, variantId: null }]);
|
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 {
|
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,
|
||||||
|
maximum_addable_quantity: 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.rows.update((rows) => rows.filter((row) => row.id !== rowId));
|
||||||
|
this.reservationRequests.delete(rowId);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected updateRow(rowId: number, selectedVariant: unknown): void {
|
private isBusy(row: TicketSelectionRow): boolean {
|
||||||
const variantId = typeof selectedVariant === 'number' ? selectedVariant : null;
|
return ['checking', 'reserving', 'removing'].includes(row.status);
|
||||||
this.rows.update((rows) => rows.map((row) => (row.id === rowId ? { ...row, variantId } : row)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected variantsForRow(rowId: number): VariantSelectorVariant[] {
|
private normalizeValue(value: CatalogVariantValue): string | string[] {
|
||||||
const selectedByOtherRows = new Set(
|
return Array.isArray(value)
|
||||||
this.rows()
|
? value.map((item) => this.scalarValue(item))
|
||||||
.filter((row) => row.id !== rowId && row.variantId !== null)
|
: this.scalarValue(value);
|
||||||
.map((row) => row.variantId),
|
}
|
||||||
);
|
|
||||||
|
|
||||||
return this.selectableVariants().filter(
|
private scalarValue(value: string | { value: string }): string {
|
||||||
(variant) => !selectedByOtherRows.has(variant.id as number),
|
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 {
|
private formatCurrency(value: number): string {
|
||||||
|
|||||||
@@ -11,13 +11,21 @@
|
|||||||
@if (!hasVariants()) {
|
@if (!hasVariants()) {
|
||||||
<div class="product-vertical-with-cart-card__summary">
|
<div class="product-vertical-with-cart-card__summary">
|
||||||
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
||||||
<app-quantity-selector [(quantity)]="quantity" />
|
<app-quantity-selector
|
||||||
|
[(quantity)]="quantity"
|
||||||
|
[max]="effectiveMaximum()"
|
||||||
|
[disabled]="unavailable()"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
} @else {
|
} @else {
|
||||||
<div class="product-vertical-with-cart-card__variants">
|
<div class="product-vertical-with-cart-card__variants">
|
||||||
<div class="product-vertical-with-cart-card__summary">
|
<div class="product-vertical-with-cart-card__summary">
|
||||||
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
||||||
<app-quantity-selector [(quantity)]="quantity" />
|
<app-quantity-selector
|
||||||
|
[(quantity)]="quantity"
|
||||||
|
[max]="effectiveMaximum()"
|
||||||
|
[disabled]="unavailable()"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="product-vertical-with-cart-card__variant-selectors">
|
<div class="product-vertical-with-cart-card__variant-selectors">
|
||||||
@@ -29,17 +37,17 @@
|
|||||||
<div class="product-vertical-with-cart-card__actions">
|
<div class="product-vertical-with-cart-card__actions">
|
||||||
<app-button
|
<app-button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
[disabled]="hasVariants() && selectedVariant() === null"
|
[disabled]="unavailable() || (hasVariants() && selectedVariant() === null)"
|
||||||
(click)="onBuy()"
|
(click)="onBuy()"
|
||||||
>
|
>
|
||||||
Comprar
|
Comprar
|
||||||
</app-button>
|
</app-button>
|
||||||
<app-button
|
<app-button
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
[disabled]="hasVariants() && selectedVariant() === null"
|
[disabled]="saving() || unavailable() || (hasVariants() && selectedVariant() === null)"
|
||||||
(click)="onAddToCart()"
|
(click)="onAddToCart()"
|
||||||
>
|
>
|
||||||
Agregar al carrito
|
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}
|
||||||
</app-button>
|
</app-button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,12 @@
|
|||||||
import { ChangeDetectionStrategy, Component, computed, input, model, output } from '@angular/core';
|
import {
|
||||||
|
ChangeDetectionStrategy,
|
||||||
|
Component,
|
||||||
|
computed,
|
||||||
|
effect,
|
||||||
|
input,
|
||||||
|
model,
|
||||||
|
output,
|
||||||
|
} from '@angular/core';
|
||||||
|
|
||||||
import { ButtonComponent } from '../button/button.component';
|
import { ButtonComponent } from '../button/button.component';
|
||||||
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
||||||
@@ -10,6 +18,7 @@ import {
|
|||||||
export interface VerticalCartVariant extends VariantSelectorVariant {
|
export interface VerticalCartVariant extends VariantSelectorVariant {
|
||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string | number;
|
precio?: string | number;
|
||||||
|
maximum_addable_quantity?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -23,7 +32,9 @@ export class ProductVerticalWithCartCardComponent {
|
|||||||
readonly title = input<string>('');
|
readonly title = input<string>('');
|
||||||
readonly description = input<string>('');
|
readonly description = input<string>('');
|
||||||
readonly price = input<number>(0);
|
readonly price = input<number>(0);
|
||||||
|
readonly maximumAddableQuantity = input<number | null>(null);
|
||||||
readonly variants = input<VerticalCartVariant[]>([]);
|
readonly variants = input<VerticalCartVariant[]>([]);
|
||||||
|
readonly saving = input(false);
|
||||||
|
|
||||||
readonly quantity = model<number>(1);
|
readonly quantity = model<number>(1);
|
||||||
readonly selectedVariant = model<number | null>(null);
|
readonly selectedVariant = model<number | null>(null);
|
||||||
@@ -44,12 +55,32 @@ export class ProductVerticalWithCartCardComponent {
|
|||||||
});
|
});
|
||||||
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||||
protected readonly hasVariants = computed(() => this.variants().length > 0);
|
protected readonly hasVariants = computed(() => this.variants().length > 0);
|
||||||
|
protected readonly effectiveMaximum = computed(
|
||||||
|
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
|
||||||
|
);
|
||||||
|
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
const maximum = this.effectiveMaximum();
|
||||||
|
|
||||||
|
if (maximum !== null && maximum > 0 && this.quantity() > maximum) {
|
||||||
|
this.quantity.set(maximum);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
protected onAddToCart(): void {
|
protected onAddToCart(): void {
|
||||||
|
if (this.saving() || this.unavailable()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.addToCart.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
|
this.addToCart.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
|
||||||
}
|
}
|
||||||
|
|
||||||
protected onBuy(): void {
|
protected onBuy(): void {
|
||||||
|
if (this.unavailable()) return;
|
||||||
|
|
||||||
this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
|
this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -114,4 +114,24 @@ describe('VariantSelectorComponent', () => {
|
|||||||
|
|
||||||
expect(fixture.componentInstance.selectedVariant()).toBe(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,6 +5,7 @@ import {
|
|||||||
effect,
|
effect,
|
||||||
input,
|
input,
|
||||||
model,
|
model,
|
||||||
|
output,
|
||||||
signal,
|
signal,
|
||||||
untracked,
|
untracked,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
@@ -23,6 +24,11 @@ export interface VariantSelectorVariant {
|
|||||||
values: Record<string, VariantAttributeValue>;
|
values: Record<string, VariantAttributeValue>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface VariantSelectorSelectionChange {
|
||||||
|
values: Record<string, VariantAttributeValue>;
|
||||||
|
selectedVariant: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
interface VariantSelectorOption {
|
interface VariantSelectorOption {
|
||||||
key: string;
|
key: string;
|
||||||
label: string;
|
label: string;
|
||||||
@@ -49,6 +55,8 @@ export class VariantSelectorComponent {
|
|||||||
readonly disabled = input(false);
|
readonly disabled = input(false);
|
||||||
readonly compact = input(false);
|
readonly compact = input(false);
|
||||||
readonly autoSelectFirst = input(true);
|
readonly autoSelectFirst = input(true);
|
||||||
|
readonly resetToken = input(0);
|
||||||
|
readonly selectionValuesChange = output<VariantSelectorSelectionChange>();
|
||||||
|
|
||||||
protected readonly selectedValues = signal<Record<string, VariantAttributeValue>>({});
|
protected readonly selectedValues = signal<Record<string, VariantAttributeValue>>({});
|
||||||
protected readonly compareValues = (
|
protected readonly compareValues = (
|
||||||
@@ -80,6 +88,27 @@ export class VariantSelectorComponent {
|
|||||||
});
|
});
|
||||||
|
|
||||||
constructor() {
|
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(() => {
|
effect(() => {
|
||||||
const variants = this.variants();
|
const variants = this.variants();
|
||||||
const selectedVariant = this.selectedVariant();
|
const selectedVariant = this.selectedVariant();
|
||||||
@@ -143,6 +172,10 @@ export class VariantSelectorComponent {
|
|||||||
|
|
||||||
this.selectedValues.set(values);
|
this.selectedValues.set(values);
|
||||||
this.selectedVariant.set(matchingVariant?.id ?? null);
|
this.selectedVariant.set(matchingVariant?.id ?? null);
|
||||||
|
this.selectionValuesChange.emit({
|
||||||
|
values: { ...values },
|
||||||
|
selectedVariant: matchingVariant?.id ?? null,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private optionsFor(variants: VariantSelectorVariant[], key: string): VariantSelectorOption[] {
|
private optionsFor(variants: VariantSelectorVariant[], key: string): VariantSelectorOption[] {
|
||||||
|
|||||||
27
src/app/shared/pages/route-not-found-page.component.ts
Normal file
27
src/app/shared/pages/route-not-found-page.component.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-route-not-found-page',
|
||||||
|
template: `
|
||||||
|
<main class="route-not-found">
|
||||||
|
<h1>404</h1>
|
||||||
|
<p>No encontramos la página solicitada.</p>
|
||||||
|
</main>
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
.route-not-found {
|
||||||
|
min-height: 100vh;
|
||||||
|
display: grid;
|
||||||
|
place-content: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 2rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1,
|
||||||
|
p {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class RouteNotFoundPageComponent {}
|
||||||
6
src/environments/environment.production.ts
Normal file
6
src/environments/environment.production.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export const environment = {
|
||||||
|
production: true,
|
||||||
|
nombre: "Producción - activo",
|
||||||
|
url: "https://backend.shopit.com.ar/api/",
|
||||||
|
urlDescarga: "url/"
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user