Compare commits
6 Commits
14bda25c56
...
feature/al
| Author | SHA1 | Date | |
|---|---|---|---|
| 72c80465e8 | |||
| 5273459b64 | |||
| 3ec469a539 | |||
| f02f4456b7 | |||
| eda8d32f4e | |||
| 5ca1f03e20 |
Binary file not shown.
@@ -1,95 +0,0 @@
|
|||||||
Copyright (c) 2011, Pablo Impallari (www.impallari.com|impallari@gmail.com),
|
|
||||||
Copyright (c) 2011, Igino Marini. (www.ikern.com|mail@iginomarini.com),
|
|
||||||
with Reserved Font Name Kaushan Script.
|
|
||||||
|
|
||||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
|
||||||
This license is copied below, and is also available with a FAQ at:
|
|
||||||
http://scripts.sil.org/OFL
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------------------------------------------
|
|
||||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
||||||
-----------------------------------------------------------
|
|
||||||
|
|
||||||
PREAMBLE
|
|
||||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
||||||
development of collaborative font projects, to support the font creation
|
|
||||||
efforts of academic and linguistic communities, and to provide a free and
|
|
||||||
open framework in which fonts may be shared and improved in partnership
|
|
||||||
with others.
|
|
||||||
|
|
||||||
The OFL allows the licensed fonts to be used, studied, modified and
|
|
||||||
redistributed freely as long as they are not sold by themselves. The
|
|
||||||
fonts, including any derivative works, can be bundled, embedded,
|
|
||||||
redistributed and/or sold with any software provided that any reserved
|
|
||||||
names are not used by derivative works. The fonts and derivatives,
|
|
||||||
however, cannot be released under any other type of license. The
|
|
||||||
requirement for fonts to remain under this license does not apply
|
|
||||||
to any document created using the fonts or their derivatives.
|
|
||||||
|
|
||||||
DEFINITIONS
|
|
||||||
"Font Software" refers to the set of files released by the Copyright
|
|
||||||
Holder(s) under this license and clearly marked as such. This may
|
|
||||||
include source files, build scripts and documentation.
|
|
||||||
|
|
||||||
"Reserved Font Name" refers to any names specified as such after the
|
|
||||||
copyright statement(s).
|
|
||||||
|
|
||||||
"Original Version" refers to the collection of Font Software components as
|
|
||||||
distributed by the Copyright Holder(s).
|
|
||||||
|
|
||||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
||||||
or substituting -- in part or in whole -- any of the components of the
|
|
||||||
Original Version, by changing formats or by porting the Font Software to a
|
|
||||||
new environment.
|
|
||||||
|
|
||||||
"Author" refers to any designer, engineer, programmer, technical
|
|
||||||
writer or other person who contributed to the Font Software.
|
|
||||||
|
|
||||||
PERMISSION & CONDITIONS
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining
|
|
||||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
|
||||||
redistribute, and sell modified and unmodified copies of the Font
|
|
||||||
Software, subject to the following conditions:
|
|
||||||
|
|
||||||
1) Neither the Font Software nor any of its individual components,
|
|
||||||
in Original or Modified Versions, may be sold by itself.
|
|
||||||
|
|
||||||
2) Original or Modified Versions of the Font Software may be bundled,
|
|
||||||
redistributed and/or sold with any software, provided that each copy
|
|
||||||
contains the above copyright notice and this license. These can be
|
|
||||||
included either as stand-alone text files, human-readable headers or
|
|
||||||
in the appropriate machine-readable metadata fields within text or
|
|
||||||
binary files as long as those fields can be easily viewed by the user.
|
|
||||||
|
|
||||||
3) No Modified Version of the Font Software may use the Reserved Font
|
|
||||||
Name(s) unless explicit written permission is granted by the corresponding
|
|
||||||
Copyright Holder. This restriction only applies to the primary font name as
|
|
||||||
presented to the users.
|
|
||||||
|
|
||||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
||||||
Software shall not be used to promote, endorse or advertise any
|
|
||||||
Modified Version, except to acknowledge the contribution(s) of the
|
|
||||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
||||||
permission.
|
|
||||||
|
|
||||||
5) The Font Software, modified or unmodified, in part or in whole,
|
|
||||||
must be distributed entirely under this license, and must not be
|
|
||||||
distributed under any other license. The requirement for fonts to
|
|
||||||
remain under this license does not apply to any document created
|
|
||||||
using the Font Software.
|
|
||||||
|
|
||||||
TERMINATION
|
|
||||||
This license becomes null and void if any of the above conditions are
|
|
||||||
not met.
|
|
||||||
|
|
||||||
DISCLAIMER
|
|
||||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
||||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
||||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
||||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
||||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
||||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
||||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
||||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
Copyright 2017 The Smooch Project Authors (https://github.com/googlefonts/smooch)
|
|
||||||
|
|
||||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
|
||||||
This license is copied below, and is also available with a FAQ at:
|
|
||||||
https://scripts.sil.org/OFL
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------------------------------------------
|
|
||||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
||||||
-----------------------------------------------------------
|
|
||||||
|
|
||||||
PREAMBLE
|
|
||||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
||||||
development of collaborative font projects, to support the font creation
|
|
||||||
efforts of academic and linguistic communities, and to provide a free and
|
|
||||||
open framework in which fonts may be shared and improved in partnership
|
|
||||||
with others.
|
|
||||||
|
|
||||||
The OFL allows the licensed fonts to be used, studied, modified and
|
|
||||||
redistributed freely as long as they are not sold by themselves. The
|
|
||||||
fonts, including any derivative works, can be bundled, embedded,
|
|
||||||
redistributed and/or sold with any software provided that any reserved
|
|
||||||
names are not used by derivative works. The fonts and derivatives,
|
|
||||||
however, cannot be released under any other type of license. The
|
|
||||||
requirement for fonts to remain under this license does not apply
|
|
||||||
to any document created using the fonts or their derivatives.
|
|
||||||
|
|
||||||
DEFINITIONS
|
|
||||||
"Font Software" refers to the set of files released by the Copyright
|
|
||||||
Holder(s) under this license and clearly marked as such. This may
|
|
||||||
include source files, build scripts and documentation.
|
|
||||||
|
|
||||||
"Reserved Font Name" refers to any names specified as such after the
|
|
||||||
copyright statement(s).
|
|
||||||
|
|
||||||
"Original Version" refers to the collection of Font Software components as
|
|
||||||
distributed by the Copyright Holder(s).
|
|
||||||
|
|
||||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
||||||
or substituting -- in part or in whole -- any of the components of the
|
|
||||||
Original Version, by changing formats or by porting the Font Software to a
|
|
||||||
new environment.
|
|
||||||
|
|
||||||
"Author" refers to any designer, engineer, programmer, technical
|
|
||||||
writer or other person who contributed to the Font Software.
|
|
||||||
|
|
||||||
PERMISSION & CONDITIONS
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining
|
|
||||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
|
||||||
redistribute, and sell modified and unmodified copies of the Font
|
|
||||||
Software, subject to the following conditions:
|
|
||||||
|
|
||||||
1) Neither the Font Software nor any of its individual components,
|
|
||||||
in Original or Modified Versions, may be sold by itself.
|
|
||||||
|
|
||||||
2) Original or Modified Versions of the Font Software may be bundled,
|
|
||||||
redistributed and/or sold with any software, provided that each copy
|
|
||||||
contains the above copyright notice and this license. These can be
|
|
||||||
included either as stand-alone text files, human-readable headers or
|
|
||||||
in the appropriate machine-readable metadata fields within text or
|
|
||||||
binary files as long as those fields can be easily viewed by the user.
|
|
||||||
|
|
||||||
3) No Modified Version of the Font Software may use the Reserved Font
|
|
||||||
Name(s) unless explicit written permission is granted by the corresponding
|
|
||||||
Copyright Holder. This restriction only applies to the primary font name as
|
|
||||||
presented to the users.
|
|
||||||
|
|
||||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
||||||
Software shall not be used to promote, endorse or advertise any
|
|
||||||
Modified Version, except to acknowledge the contribution(s) of the
|
|
||||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
||||||
permission.
|
|
||||||
|
|
||||||
5) The Font Software, modified or unmodified, in part or in whole,
|
|
||||||
must be distributed entirely under this license, and must not be
|
|
||||||
distributed under any other license. The requirement for fonts to
|
|
||||||
remain under this license does not apply to any document created
|
|
||||||
using the Font Software.
|
|
||||||
|
|
||||||
TERMINATION
|
|
||||||
This license becomes null and void if any of the above conditions are
|
|
||||||
not met.
|
|
||||||
|
|
||||||
DISCLAIMER
|
|
||||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
||||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
||||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
||||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
||||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
||||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
||||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
||||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
|
||||||
Binary file not shown.
@@ -1,11 +1,3 @@
|
|||||||
@font-face {
|
|
||||||
font-family: 'Smooch';
|
|
||||||
src: url('/fonts/Smooch/Smooch-Regular.ttf') format('truetype');
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 400;
|
|
||||||
font-display: swap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: "Gotham";
|
font-family: "Gotham";
|
||||||
src: url("/fonts/Gotham/Gotham Thin.otf") format("opentype");
|
src: url("/fonts/Gotham/Gotham Thin.otf") format("opentype");
|
||||||
@@ -38,14 +30,6 @@
|
|||||||
font-display: swap;
|
font-display: swap;
|
||||||
}
|
}
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: "Gotham Book";
|
|
||||||
src: url("/fonts/Gotham/Gotham Book.otf") format("opentype");
|
|
||||||
font-weight: 400;
|
|
||||||
font-style: normal;
|
|
||||||
font-display: swap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: "Gotham";
|
font-family: "Gotham";
|
||||||
src: url("/fonts/Gotham/Gotham Italic.otf") format("opentype");
|
src: url("/fonts/Gotham/Gotham Italic.otf") format("opentype");
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ describe('isStoreCatalogRequest', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it.each([
|
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/productos'],
|
||||||
['GET', 'http://localhost:8000/api/tenants/demo/categories/7'],
|
['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/catalog-items/42/variant-options'],
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import { TenantUrlSerializer } from './core/services/tenant-url.serializer';
|
|||||||
export function isStoreCatalogRequest(request: HttpRequest<unknown>): boolean {
|
export function isStoreCatalogRequest(request: HttpRequest<unknown>): boolean {
|
||||||
return (
|
return (
|
||||||
request.method === 'GET' &&
|
request.method === 'GET' &&
|
||||||
/\/api\/tenants\/[^/?#]+\/(?:catalog(?:\/featured-groups\/\d+\/items)?|catalog-items(?:\/\d+)?|events(?:\/\d+)?)\/?(?:[?#]|$)/.test(
|
/\/api\/tenants\/[^/?#]+\/(?:catalog(?:\/featured-groups\/\d+\/items)?|catalog-items(?:\/\d+)?)\/?(?:[?#]|$)/.test(
|
||||||
request.urlWithParams,
|
request.urlWithParams,
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { of } from 'rxjs';
|
|||||||
import { App } from './app';
|
import { App } from './app';
|
||||||
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 { CheckoutService } 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 { routes } from './app.routes';
|
import { routes } from './app.routes';
|
||||||
@@ -98,21 +97,6 @@ async function renderAppAt(
|
|||||||
{
|
{
|
||||||
provide: AuthService,
|
provide: AuthService,
|
||||||
useValue: authService
|
useValue: authService
|
||||||
},
|
|
||||||
{
|
|
||||||
provide: CheckoutService,
|
|
||||||
useValue: {
|
|
||||||
withCustomLoading() {
|
|
||||||
return this;
|
|
||||||
},
|
|
||||||
getPurchase: vi.fn().mockResolvedValue({
|
|
||||||
id: 25,
|
|
||||||
status: 'created',
|
|
||||||
items: [],
|
|
||||||
subtotal: '0.00',
|
|
||||||
total: '0.00'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
@@ -262,33 +246,15 @@ 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('redirects unauthenticated users from /checkout/:id to /login', async () => {
|
it('redirects unauthenticated users from /checkout to /login', async () => {
|
||||||
const { router } = await renderAppAt('/checkout/25', createTenantServiceStub(), createAuthServiceStub(false));
|
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false));
|
||||||
|
|
||||||
expect(router.url).toBe('/login?returnUrl=%2Fcheckout%2F25');
|
expect(router.url).toBe('/login?returnUrl=%2Fcheckout');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('allows authenticated users to access /checkout/:id', async () => {
|
it('allows authenticated users to access /checkout', async () => {
|
||||||
const checkoutTenant = {
|
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(true));
|
||||||
...tenant,
|
|
||||||
menues: [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
code: 'checkout',
|
|
||||||
label: 'Checkout',
|
|
||||||
parent_menu_code: null,
|
|
||||||
content_type: 'dynamic' as const,
|
|
||||||
route: '/checkout',
|
|
||||||
submenues: []
|
|
||||||
}
|
|
||||||
]
|
|
||||||
};
|
|
||||||
const { router } = await renderAppAt(
|
|
||||||
'/checkout/25',
|
|
||||||
createTenantServiceStub('ready', checkoutTenant),
|
|
||||||
createAuthServiceStub(true)
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(router.url).toBe('/checkout/25');
|
expect(router.url).toBe('/checkout');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import '@angular/compiler';
|
import '@angular/compiler';
|
||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
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 { provideRouter } from '@angular/router';
|
import { provideRouter } from '@angular/router';
|
||||||
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
@@ -24,7 +27,7 @@ const tenant: Tenant = {
|
|||||||
footer_bg_color: '#313131',
|
footer_bg_color: '#313131',
|
||||||
header_logo: 'https://example.com/header.png',
|
header_logo: 'https://example.com/header.png',
|
||||||
footer_logo: 'https://example.com/footer.png',
|
footer_logo: 'https://example.com/footer.png',
|
||||||
categories: [],
|
categories: []
|
||||||
};
|
};
|
||||||
|
|
||||||
function createTenantServiceStub(status: 'ready' | 'not-found', currentTenant: Tenant | null) {
|
function createTenantServiceStub(status: 'ready' | 'not-found', currentTenant: Tenant | null) {
|
||||||
@@ -35,14 +38,17 @@ function createTenantServiceStub(status: 'ready' | 'not-found', currentTenant: T
|
|||||||
tenant: tenantState.asReadonly(),
|
tenant: tenantState.asReadonly(),
|
||||||
status: statusState.asReadonly(),
|
status: statusState.asReadonly(),
|
||||||
getTenant: () => tenantState(),
|
getTenant: () => tenantState(),
|
||||||
bootstrap: vi.fn().mockResolvedValue(undefined),
|
bootstrap: vi.fn().mockResolvedValue(undefined)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('App', () => {
|
describe('App', () => {
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
try {
|
try {
|
||||||
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
|
getTestBed().initTestEnvironment(
|
||||||
|
BrowserTestingModule,
|
||||||
|
platformBrowserTesting()
|
||||||
|
);
|
||||||
} catch {
|
} catch {
|
||||||
// Test environment may already be initialized by another setup entrypoint.
|
// Test environment may already be initialized by another setup entrypoint.
|
||||||
}
|
}
|
||||||
@@ -59,9 +65,9 @@ describe('App', () => {
|
|||||||
provideRouter([]),
|
provideRouter([]),
|
||||||
{
|
{
|
||||||
provide: TenantService,
|
provide: TenantService,
|
||||||
useValue: createTenantServiceStub('ready', tenant),
|
useValue: createTenantServiceStub('ready', tenant)
|
||||||
},
|
}
|
||||||
],
|
]
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(App);
|
const fixture = TestBed.createComponent(App);
|
||||||
@@ -69,27 +75,26 @@ describe('App', () => {
|
|||||||
|
|
||||||
expect(fixture.componentInstance).toBeTruthy();
|
expect(fixture.componentInstance).toBeTruthy();
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-primary')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-primary')).toBe(
|
||||||
tenant.primary_color,
|
tenant.primary_color
|
||||||
);
|
);
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-secondary')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-secondary')).toBe(
|
||||||
tenant.secondary_color,
|
tenant.secondary_color
|
||||||
);
|
);
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-danger')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-danger')).toBe(
|
||||||
tenant.danger_color,
|
tenant.danger_color
|
||||||
);
|
);
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-primary-rgb')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-primary-rgb')).toBe(
|
||||||
'99, 118, 243',
|
'99, 118, 243'
|
||||||
);
|
);
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-secondary-rgb')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-secondary-rgb')).toBe(
|
||||||
'160, 160, 160',
|
'160, 160, 160'
|
||||||
);
|
);
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-danger-rgb')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-danger-rgb')).toBe(
|
||||||
'255, 136, 136',
|
'255, 136, 136'
|
||||||
);
|
);
|
||||||
expect(document.title).toBe(tenant.site_title);
|
expect(document.title).toBe(tenant.site_title);
|
||||||
expect(
|
expect(document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'))
|
||||||
document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'),
|
.toBe(tenant.favicon);
|
||||||
).toBe(tenant.favicon);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders the tenant not found screen when the tenant is missing', async () => {
|
it('renders the tenant not found screen when the tenant is missing', async () => {
|
||||||
@@ -99,21 +104,17 @@ describe('App', () => {
|
|||||||
provideRouter([]),
|
provideRouter([]),
|
||||||
{
|
{
|
||||||
provide: TenantService,
|
provide: TenantService,
|
||||||
useValue: createTenantServiceStub('not-found', null),
|
useValue: createTenantServiceStub('not-found', null)
|
||||||
},
|
}
|
||||||
],
|
]
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(App);
|
const fixture = TestBed.createComponent(App);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(fixture.nativeElement.textContent).toContain(
|
expect(fixture.nativeElement.textContent).toContain('No encontramos una tienda para este dominio');
|
||||||
'No encontramos una tienda para este dominio',
|
|
||||||
);
|
|
||||||
expect(document.title).toBe('ShopitFront');
|
expect(document.title).toBe('ShopitFront');
|
||||||
expect(
|
expect(document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'))
|
||||||
document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'),
|
.toBe('favicon.ico');
|
||||||
).toBe("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,13 +9,9 @@ import { GlobalLoadingComponent } from './shared/components/global-loading/globa
|
|||||||
import { ModalHostComponent } from './shared/components/modal-host/modal-host.component';
|
import { ModalHostComponent } from './shared/components/modal-host/modal-host.component';
|
||||||
import { ToastContainerComponent } from './shared/components/toast-container/toast-container.component';
|
import { ToastContainerComponent } from './shared/components/toast-container/toast-container.component';
|
||||||
|
|
||||||
const EMPTY_FAVICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E";
|
|
||||||
|
|
||||||
function hexToRgb(hex: string): string {
|
function hexToRgb(hex: string): string {
|
||||||
const cleanHex = hex.replace('#', '').trim();
|
const cleanHex = hex.replace('#', '').trim();
|
||||||
let r = 0,
|
let r = 0, g = 0, b = 0;
|
||||||
g = 0,
|
|
||||||
b = 0;
|
|
||||||
if (cleanHex.length === 3) {
|
if (cleanHex.length === 3) {
|
||||||
r = parseInt(cleanHex[0] + cleanHex[0], 16);
|
r = parseInt(cleanHex[0] + cleanHex[0], 16);
|
||||||
g = parseInt(cleanHex[1] + cleanHex[1], 16);
|
g = parseInt(cleanHex[1] + cleanHex[1], 16);
|
||||||
@@ -30,7 +26,12 @@ function hexToRgb(hex: string): string {
|
|||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-root',
|
selector: 'app-root',
|
||||||
imports: [RouterOutlet, ToastContainerComponent, ModalHostComponent, GlobalLoadingComponent],
|
imports: [
|
||||||
|
RouterOutlet,
|
||||||
|
ToastContainerComponent,
|
||||||
|
ModalHostComponent,
|
||||||
|
GlobalLoadingComponent
|
||||||
|
],
|
||||||
templateUrl: './app.html',
|
templateUrl: './app.html',
|
||||||
styleUrl: './app.scss',
|
styleUrl: './app.scss',
|
||||||
host: {
|
host: {
|
||||||
@@ -53,8 +54,8 @@ function hexToRgb(hex: string): string {
|
|||||||
'[style.--tenant-header-bg]': 'tenantHeaderBgColor()',
|
'[style.--tenant-header-bg]': 'tenantHeaderBgColor()',
|
||||||
'[style.--tenant-footer-bg]': 'tenantFooterBgColor()',
|
'[style.--tenant-footer-bg]': 'tenantFooterBgColor()',
|
||||||
'[style.--color-header-bg]': 'tenantHeaderBgColor()',
|
'[style.--color-header-bg]': 'tenantHeaderBgColor()',
|
||||||
'[style.--color-footer-bg]': 'tenantFooterBgColor()',
|
'[style.--color-footer-bg]': 'tenantFooterBgColor()'
|
||||||
},
|
}
|
||||||
})
|
})
|
||||||
export class App {
|
export class App {
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
@@ -65,7 +66,7 @@ export class App {
|
|||||||
effect(() => {
|
effect(() => {
|
||||||
const tenant = this.tenantService.tenant();
|
const tenant = this.tenantService.tenant();
|
||||||
const siteTitle = tenant?.site_title?.trim() || 'ShopitFront';
|
const siteTitle = tenant?.site_title?.trim() || 'ShopitFront';
|
||||||
const faviconHref = tenant?.favicon || EMPTY_FAVICON;
|
const faviconHref = tenant?.favicon || 'favicon.ico';
|
||||||
|
|
||||||
this.title.setTitle(siteTitle);
|
this.title.setTitle(siteTitle);
|
||||||
|
|
||||||
@@ -84,27 +85,37 @@ export class App {
|
|||||||
protected readonly status = this.tenantService.status;
|
protected readonly status = this.tenantService.status;
|
||||||
|
|
||||||
protected readonly tenantPrimaryColor = computed(
|
protected readonly tenantPrimaryColor = computed(
|
||||||
() => this.tenantService.tenant()?.primary_color ?? DEFAULT_TENANT_BRANDING.primaryColor,
|
() => this.tenantService.tenant()?.primary_color ?? DEFAULT_TENANT_BRANDING.primaryColor
|
||||||
);
|
);
|
||||||
protected readonly tenantSecondaryColor = computed(
|
protected readonly tenantSecondaryColor = computed(
|
||||||
() => this.tenantService.tenant()?.secondary_color ?? DEFAULT_TENANT_BRANDING.secondaryColor,
|
() => this.tenantService.tenant()?.secondary_color ?? DEFAULT_TENANT_BRANDING.secondaryColor
|
||||||
);
|
);
|
||||||
protected readonly tenantDangerColor = computed(
|
protected readonly tenantDangerColor = computed(
|
||||||
() => this.tenantService.tenant()?.danger_color ?? DEFAULT_TENANT_BRANDING.dangerColor,
|
() => this.tenantService.tenant()?.danger_color ?? DEFAULT_TENANT_BRANDING.dangerColor
|
||||||
);
|
);
|
||||||
protected readonly tenantSuccessColor = computed(
|
protected readonly tenantSuccessColor = computed(
|
||||||
() => this.tenantService.tenant()?.success_color ?? DEFAULT_TENANT_BRANDING.successColor,
|
() => this.tenantService.tenant()?.success_color ?? DEFAULT_TENANT_BRANDING.successColor
|
||||||
|
);
|
||||||
|
protected readonly tenantPrimaryColorRgb = computed(() =>
|
||||||
|
hexToRgb(this.tenantPrimaryColor())
|
||||||
);
|
);
|
||||||
protected readonly tenantPrimaryColorRgb = computed(() => hexToRgb(this.tenantPrimaryColor()));
|
|
||||||
protected readonly tenantSecondaryColorRgb = computed(() =>
|
protected readonly tenantSecondaryColorRgb = computed(() =>
|
||||||
hexToRgb(this.tenantSecondaryColor()),
|
hexToRgb(this.tenantSecondaryColor())
|
||||||
|
);
|
||||||
|
protected readonly tenantDangerColorRgb = computed(() =>
|
||||||
|
hexToRgb(this.tenantDangerColor())
|
||||||
|
);
|
||||||
|
protected readonly tenantSuccessColorRgb = computed(() =>
|
||||||
|
hexToRgb(this.tenantSuccessColor())
|
||||||
);
|
);
|
||||||
protected readonly tenantDangerColorRgb = computed(() => hexToRgb(this.tenantDangerColor()));
|
|
||||||
protected readonly tenantSuccessColorRgb = computed(() => hexToRgb(this.tenantSuccessColor()));
|
|
||||||
protected readonly tenantHeaderBgColor = computed(
|
protected readonly tenantHeaderBgColor = computed(
|
||||||
() => this.tenantService.tenant()?.header_bg_color ?? DEFAULT_TENANT_BRANDING.headerBgColor,
|
() =>
|
||||||
|
this.tenantService.tenant()?.header_bg_color ??
|
||||||
|
DEFAULT_TENANT_BRANDING.headerBgColor
|
||||||
);
|
);
|
||||||
protected readonly tenantFooterBgColor = computed(
|
protected readonly tenantFooterBgColor = computed(
|
||||||
() => this.tenantService.tenant()?.footer_bg_color ?? DEFAULT_TENANT_BRANDING.footerBgColor,
|
() =>
|
||||||
|
this.tenantService.tenant()?.footer_bg_color ??
|
||||||
|
DEFAULT_TENANT_BRANDING.footerBgColor
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideRouter, Router, UrlSerializer, UrlTree } from '@angular/router';
|
import { provideRouter, Router, UrlTree } from '@angular/router';
|
||||||
|
|
||||||
import { Tenant } from '../services/tenant.interface';
|
import { Tenant } from '../services/tenant.interface';
|
||||||
import { TenantService } from '../services/tenant.service';
|
import { TenantService } from '../services/tenant.service';
|
||||||
import { TenantUrlSerializer } from '../services/tenant-url.serializer';
|
|
||||||
import { hasMenuGuard } from './menu.guard';
|
import { hasMenuGuard } from './menu.guard';
|
||||||
|
|
||||||
const tenant: Tenant = {
|
const tenant: Tenant = {
|
||||||
@@ -37,10 +36,9 @@ function runGuard(menuCode: string, url: string, currentTenant: Tenant | null) {
|
|||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
provideRouter([]),
|
provideRouter([]),
|
||||||
{ provide: UrlSerializer, useClass: TenantUrlSerializer },
|
|
||||||
{
|
{
|
||||||
provide: TenantService,
|
provide: TenantService,
|
||||||
useValue: { tenant: () => currentTenant, getTenant: () => currentTenant },
|
useValue: { tenant: () => currentTenant },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
@@ -64,7 +62,7 @@ describe('hasMenuGuard', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('redirects a missing menu route to the store root', () => {
|
it('redirects a missing menu route to the store root', () => {
|
||||||
const result = runGuard('checkout', '/checkout/25', tenant);
|
const result = runGuard('checkout', '/checkout', tenant);
|
||||||
|
|
||||||
expect(result instanceof UrlTree).toBe(true);
|
expect(result instanceof UrlTree).toBe(true);
|
||||||
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/');
|
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/');
|
||||||
@@ -75,16 +73,4 @@ describe('hasMenuGuard', () => {
|
|||||||
|
|
||||||
expect(runGuard('index', '/', tenantWithoutMenus)).toBe(true);
|
expect(runGuard('index', '/', tenantWithoutMenus)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('allows a tenant base path as the store root when its menu is missing', () => {
|
|
||||||
const tenantWithoutMenus = { ...tenant, base_path: '/onticket', menues: [] };
|
|
||||||
|
|
||||||
expect(runGuard('index', '/onticket', tenantWithoutMenus)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('allows a tenant base path with query parameters as the store root', () => {
|
|
||||||
const tenantWithoutMenus = { ...tenant, base_path: '/onticket', menues: [] };
|
|
||||||
|
|
||||||
expect(runGuard('index', '/onticket?ref=home', tenantWithoutMenus)).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { inject } from '@angular/core';
|
import { inject } from '@angular/core';
|
||||||
import { CanActivateFn, PRIMARY_OUTLET, Router } from '@angular/router';
|
import { CanActivateFn, Router } from '@angular/router';
|
||||||
import { findMenu } from '../services/menu.utils';
|
import { findMenu } from '../services/menu.utils';
|
||||||
import { TenantService } from '../services/tenant.service';
|
import { TenantService } from '../services/tenant.service';
|
||||||
|
|
||||||
@@ -16,9 +16,7 @@ export const hasMenuGuard = (menuCode: string): CanActivateFn => {
|
|||||||
|
|
||||||
const hasMenu = findMenu(tenant.menues ?? [], menuCode) !== undefined;
|
const hasMenu = findMenu(tenant.menues ?? [], menuCode) !== undefined;
|
||||||
|
|
||||||
const primarySegments = router.parseUrl(state.url).root.children[PRIMARY_OUTLET]?.segments ?? [];
|
if (hasMenu || state.url === '/') {
|
||||||
|
|
||||||
if (hasMenu || primarySegments.length === 0) {
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,103 +0,0 @@
|
|||||||
<header
|
|
||||||
class="immersive-header"
|
|
||||||
[class.immersive-header--compact]="!showHero()"
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
class="immersive-header__backdrop"
|
|
||||||
[style.background-image]="backgroundImageUrl() ? 'url(' + backgroundImageUrl() + ')' : null"
|
|
||||||
></div>
|
|
||||||
|
|
||||||
<div class="immersive-header__content">
|
|
||||||
<nav class="immersive-header__nav container-xl px-3 px-md-4" aria-label="Navegación de la tienda">
|
|
||||||
<a routerLink="/" class="immersive-header__brand" aria-label="Ir al inicio">
|
|
||||||
@if (logoUrl()) {
|
|
||||||
<img [src]="logoUrl()" alt="Logo del comercio" />
|
|
||||||
}
|
|
||||||
</a>
|
|
||||||
|
|
||||||
<div class="immersive-header__actions">
|
|
||||||
@if (displaySearchBar()) {
|
|
||||||
<form class="immersive-header__search" role="search" (submit)="submitSearch($event)">
|
|
||||||
<label class="visually-hidden" for="immersive-search-input">Buscar productos</label>
|
|
||||||
<input
|
|
||||||
id="immersive-search-input"
|
|
||||||
type="search"
|
|
||||||
placeholder="Buscar"
|
|
||||||
autocomplete="off"
|
|
||||||
[formControl]="searchControl"
|
|
||||||
[attr.aria-invalid]="showSearchError()"
|
|
||||||
[attr.aria-describedby]="showSearchError() ? 'immersive-search-error' : null"
|
|
||||||
(input)="showSearchError.set(false)"
|
|
||||||
/>
|
|
||||||
<button type="submit" aria-label="Buscar">
|
|
||||||
<i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
|
|
||||||
</button>
|
|
||||||
@if (showSearchError()) {
|
|
||||||
<span id="immersive-search-error" class="immersive-header__search-error" role="alert"
|
|
||||||
>Ingresá al menos 3 caracteres.</span
|
|
||||||
>
|
|
||||||
}
|
|
||||||
</form>
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (ticketsMenu(); as menu) {
|
|
||||||
<button class="immersive-header__tickets" type="button" (click)="ticketsClick.emit()">
|
|
||||||
{{ menu.label }}
|
|
||||||
</button>
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (displayCart()) {
|
|
||||||
<app-cart-icon
|
|
||||||
[quantity]="cartDisabled() ? null : cartQuantity()"
|
|
||||||
[disabled]="cartDisabled()"
|
|
||||||
[ariaLabel]="
|
|
||||||
cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito de compras'
|
|
||||||
"
|
|
||||||
(click)="onCartClick()"
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
|
|
||||||
<div class="immersive-header__account">
|
|
||||||
<app-icon-button
|
|
||||||
variant="user"
|
|
||||||
ariaLabel="Mi cuenta"
|
|
||||||
ariaControls="immersive-user-dropdown"
|
|
||||||
[ariaExpanded]="isUserDropdownOpen()"
|
|
||||||
(clicked)="toggleUserDropdown()"
|
|
||||||
/>
|
|
||||||
@if (isUserDropdownOpen()) {
|
|
||||||
<app-user-dropdown
|
|
||||||
id="immersive-user-dropdown"
|
|
||||||
[user]="user()"
|
|
||||||
[accountNavigationMenus]="accountNavigationMenus()"
|
|
||||||
(logoutClick)="onLogoutClick()"
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
@if (checkoutRemainingTime(); as remainingTime) {
|
|
||||||
<div class="immersive-header__timer container-xl px-3 px-md-4" role="timer" aria-label="Tiempo restante de compra">
|
|
||||||
Tiempo restante de compra: <strong>{{ remainingTime }}</strong>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (showHero()) {
|
|
||||||
@if (heroContent(); as content) {
|
|
||||||
<div class="immersive-header__copy">
|
|
||||||
<p class="immersive-header__eyebrow">{{ content.eyebrow }}</p>
|
|
||||||
<h1 class="immersive-header__title">{{ content.title }}</h1>
|
|
||||||
<p class="immersive-header__description">{{ content.description }}</p>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (carouselImages().length) {
|
|
||||||
<app-continuous-image-carousel
|
|
||||||
[images]="carouselImages()"
|
|
||||||
ariaLabel="Imágenes del evento"
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
@@ -1,224 +0,0 @@
|
|||||||
:host {
|
|
||||||
display: block;
|
|
||||||
}
|
|
||||||
|
|
||||||
.immersive-header {
|
|
||||||
position: relative;
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: minmax(0, 1fr);
|
|
||||||
isolation: isolate;
|
|
||||||
min-height: 640px;
|
|
||||||
color: #fff;
|
|
||||||
background: #f5f5f5;
|
|
||||||
}
|
|
||||||
|
|
||||||
.immersive-header__content {
|
|
||||||
grid-area: 1 / 1;
|
|
||||||
position: relative;
|
|
||||||
z-index: 1;
|
|
||||||
min-width: 0;
|
|
||||||
padding-top: clamp(1.75rem, 4vw, 2.5rem);
|
|
||||||
padding-bottom: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.immersive-header__backdrop {
|
|
||||||
grid-area: 1 / 1;
|
|
||||||
position: relative;
|
|
||||||
z-index: 0;
|
|
||||||
background-color: #101010;
|
|
||||||
background-position: center 42%;
|
|
||||||
background-size: cover;
|
|
||||||
}
|
|
||||||
|
|
||||||
.immersive-header__backdrop::after {
|
|
||||||
content: '';
|
|
||||||
position: absolute;
|
|
||||||
inset: 0;
|
|
||||||
background: linear-gradient(
|
|
||||||
180deg,
|
|
||||||
rgba(0, 0, 0, 0.48) 0%,
|
|
||||||
rgba(0, 0, 0, 0.4) 47%,
|
|
||||||
#f5f5f5 100%
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
.immersive-header__nav {
|
|
||||||
position: relative;
|
|
||||||
z-index: 1;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 1.5rem;
|
|
||||||
min-height: 2.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.immersive-header__brand {
|
|
||||||
display: inline-flex;
|
|
||||||
flex: none;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
.immersive-header__brand img {
|
|
||||||
display: block;
|
|
||||||
width: clamp(105px, 13vw, 145px);
|
|
||||||
max-height: 2.25rem;
|
|
||||||
object-fit: contain;
|
|
||||||
}
|
|
||||||
.immersive-header__actions {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: clamp(0.35rem, 1vw, 1rem);
|
|
||||||
}
|
|
||||||
|
|
||||||
.immersive-header__search {
|
|
||||||
position: relative;
|
|
||||||
display: flex;
|
|
||||||
width: clamp(115px, 17vw, 205px);
|
|
||||||
height: 2rem;
|
|
||||||
border: 1px solid var(--tenant-primary, #ff7006);
|
|
||||||
border-radius: 3px;
|
|
||||||
background: rgba(0, 0, 0, 0.1);
|
|
||||||
}
|
|
||||||
.immersive-header__search input {
|
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
padding: 0 0.5rem;
|
|
||||||
border: 0;
|
|
||||||
outline: 0;
|
|
||||||
color: #fff;
|
|
||||||
background: transparent;
|
|
||||||
font-size: 0.75rem;
|
|
||||||
}
|
|
||||||
.immersive-header__search input::placeholder {
|
|
||||||
color: rgba(255, 255, 255, 0.78);
|
|
||||||
}
|
|
||||||
.immersive-header__search input::-webkit-search-cancel-button {
|
|
||||||
filter: invert(1);
|
|
||||||
}
|
|
||||||
.immersive-header__search button {
|
|
||||||
border: 0;
|
|
||||||
padding-inline: 0.55rem;
|
|
||||||
color: var(--tenant-primary, #ff7006);
|
|
||||||
background: transparent;
|
|
||||||
}
|
|
||||||
.immersive-header__search:focus-within {
|
|
||||||
outline: 2px solid var(--tenant-primary, #ff7006);
|
|
||||||
outline-offset: 2px;
|
|
||||||
}
|
|
||||||
.immersive-header__search-error {
|
|
||||||
position: absolute;
|
|
||||||
top: calc(100% + 0.25rem);
|
|
||||||
right: 0;
|
|
||||||
width: max-content;
|
|
||||||
color: #fff;
|
|
||||||
font-size: 0.7rem;
|
|
||||||
}
|
|
||||||
.immersive-header__tickets {
|
|
||||||
border: 1px solid var(--tenant-primary, #ff7006);
|
|
||||||
border-radius: 3px;
|
|
||||||
padding: 0.25rem 0.6rem;
|
|
||||||
color: #fff;
|
|
||||||
background: rgba(0, 0, 0, 0.2);
|
|
||||||
font-size: 0.75rem;
|
|
||||||
}
|
|
||||||
.immersive-header__tickets:hover {
|
|
||||||
background: var(--tenant-primary, #ff7006);
|
|
||||||
}
|
|
||||||
.immersive-header__account {
|
|
||||||
position: relative;
|
|
||||||
display: flex;
|
|
||||||
}
|
|
||||||
.immersive-header__account app-user-dropdown {
|
|
||||||
position: absolute;
|
|
||||||
top: 100%;
|
|
||||||
right: 0;
|
|
||||||
z-index: 20;
|
|
||||||
color: #222;
|
|
||||||
}
|
|
||||||
:host ::ng-deep .immersive-header__actions .icon-btn,
|
|
||||||
:host ::ng-deep .immersive-header__actions .cart-icon {
|
|
||||||
color: var(--tenant-primary, #ff7006);
|
|
||||||
}
|
|
||||||
|
|
||||||
.immersive-header__copy {
|
|
||||||
position: relative;
|
|
||||||
z-index: 1;
|
|
||||||
margin: clamp(2.1rem, 5vw, 3.25rem) auto 0;
|
|
||||||
padding-inline: 1rem;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
.immersive-header__eyebrow,
|
|
||||||
.immersive-header__title {
|
|
||||||
font-family: 'Smooch', cursive;
|
|
||||||
font-weight: 400;
|
|
||||||
text-shadow: 0 2px 12px rgba(0, 0, 0, 0.55);
|
|
||||||
}
|
|
||||||
.immersive-header__eyebrow {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 50px;
|
|
||||||
line-height: 1;
|
|
||||||
}
|
|
||||||
.immersive-header__title {
|
|
||||||
margin: -0.15rem 0 0;
|
|
||||||
font-size: 140px;
|
|
||||||
line-height: 1.05;
|
|
||||||
}
|
|
||||||
.immersive-header__description {
|
|
||||||
margin: 1.15rem 0 0;
|
|
||||||
font-size: clamp(0.75rem, 1.4vw, 0.95rem);
|
|
||||||
text-shadow: 0 1px 5px rgba(0, 0, 0, 0.6);
|
|
||||||
}
|
|
||||||
.immersive-header__timer {
|
|
||||||
position: relative;
|
|
||||||
z-index: 1;
|
|
||||||
margin-top: 0.75rem;
|
|
||||||
text-align: right;
|
|
||||||
font-size: 0.75rem;
|
|
||||||
}
|
|
||||||
.immersive-header app-continuous-image-carousel {
|
|
||||||
display: block;
|
|
||||||
position: relative;
|
|
||||||
z-index: 1;
|
|
||||||
margin-top: clamp(3.25rem, 7vw, 5rem);
|
|
||||||
}
|
|
||||||
|
|
||||||
.immersive-header--compact {
|
|
||||||
min-height: 0;
|
|
||||||
padding-bottom: 1.5rem;
|
|
||||||
background: #171717;
|
|
||||||
}
|
|
||||||
.immersive-header--compact .immersive-header__backdrop {
|
|
||||||
position: absolute;
|
|
||||||
inset: 0;
|
|
||||||
}
|
|
||||||
.immersive-header--compact .immersive-header__backdrop::after {
|
|
||||||
background: rgba(0, 0, 0, 0.65);
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 600px) {
|
|
||||||
.immersive-header__nav {
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 0.5rem;
|
|
||||||
}
|
|
||||||
.immersive-header__actions {
|
|
||||||
flex: 1;
|
|
||||||
justify-content: flex-end;
|
|
||||||
}
|
|
||||||
.immersive-header__search {
|
|
||||||
width: clamp(105px, 38vw, 180px);
|
|
||||||
}
|
|
||||||
.immersive-header__copy {
|
|
||||||
margin-top: 3rem;
|
|
||||||
}
|
|
||||||
.immersive-header__eyebrow {
|
|
||||||
font-size: clamp(2rem, 8vw, 50px);
|
|
||||||
}
|
|
||||||
.immersive-header__title {
|
|
||||||
font-size: clamp(3rem, 12vw, 5rem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
|
||||||
.immersive-header__tickets {
|
|
||||||
transition: none;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
import {
|
|
||||||
Component,
|
|
||||||
ElementRef,
|
|
||||||
HostListener,
|
|
||||||
computed,
|
|
||||||
inject,
|
|
||||||
input,
|
|
||||||
output,
|
|
||||||
signal,
|
|
||||||
} from '@angular/core';
|
|
||||||
import { FormControl, ReactiveFormsModule } from '@angular/forms';
|
|
||||||
import { RouterLink } from '@angular/router';
|
|
||||||
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
|
||||||
import { Menu, WebsiteExtras } from '../../../services/tenant.interface';
|
|
||||||
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
|
|
||||||
import { IconButtonComponent } from '../../../../shared/components/icon-button/icon-button.component';
|
|
||||||
import { ContinuousImageCarouselComponent } from '../../../../shared/components/continuous-image-carousel/continuous-image-carousel.component';
|
|
||||||
import { UserDropdownComponent } from './user-dropdown/user-dropdown.component';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'app-immersive-store-header',
|
|
||||||
imports: [
|
|
||||||
RouterLink,
|
|
||||||
ReactiveFormsModule,
|
|
||||||
CartIconComponent,
|
|
||||||
IconButtonComponent,
|
|
||||||
ContinuousImageCarouselComponent,
|
|
||||||
UserDropdownComponent,
|
|
||||||
],
|
|
||||||
templateUrl: './immersive-store-header.component.html',
|
|
||||||
styleUrl: './immersive-store-header.component.scss',
|
|
||||||
})
|
|
||||||
export class ImmersiveStoreHeaderComponent {
|
|
||||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
|
||||||
|
|
||||||
readonly logoUrl = input<string | null>(null);
|
|
||||||
readonly backgroundImageUrl = input<string | null>(null);
|
|
||||||
readonly heroContent = input<WebsiteExtras['immersiveHero']>(undefined);
|
|
||||||
readonly carouselImages = input<readonly string[]>([]);
|
|
||||||
readonly showHero = input(true);
|
|
||||||
readonly cartQuantity = input(0);
|
|
||||||
readonly user = input<AuthUser | null>(null);
|
|
||||||
readonly isAuthenticated = input(false);
|
|
||||||
readonly accountNavigationMenus = input<readonly Menu[]>([]);
|
|
||||||
readonly ticketsMenu = input<Menu | null>(null);
|
|
||||||
readonly displaySearchBar = input(true);
|
|
||||||
readonly displayCart = input(true);
|
|
||||||
readonly cartDisabled = input(false);
|
|
||||||
readonly checkoutRemainingSeconds = input<number | null>(null);
|
|
||||||
|
|
||||||
readonly cartClick = output<void>();
|
|
||||||
readonly ticketsClick = output<void>();
|
|
||||||
readonly loginClick = output<void>();
|
|
||||||
readonly logoutClick = output<void>();
|
|
||||||
readonly searchSubmit = output<string>();
|
|
||||||
|
|
||||||
protected readonly searchControl = new FormControl('', { nonNullable: true });
|
|
||||||
protected readonly showSearchError = signal(false);
|
|
||||||
protected readonly isUserDropdownOpen = signal(false);
|
|
||||||
protected readonly checkoutRemainingTime = computed(() => {
|
|
||||||
const seconds = this.checkoutRemainingSeconds();
|
|
||||||
if (seconds === null) return null;
|
|
||||||
|
|
||||||
return `${Math.floor(seconds / 60)
|
|
||||||
.toString()
|
|
||||||
.padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
|
|
||||||
});
|
|
||||||
|
|
||||||
protected submitSearch(event?: Event): void {
|
|
||||||
event?.preventDefault();
|
|
||||||
const term = this.searchControl.value.trim();
|
|
||||||
if (term.length < 3) {
|
|
||||||
this.showSearchError.set(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.showSearchError.set(false);
|
|
||||||
this.searchSubmit.emit(term);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected toggleUserDropdown(): void {
|
|
||||||
if (!this.isAuthenticated()) {
|
|
||||||
this.loginClick.emit();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.isUserDropdownOpen.update((open) => !open);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onCartClick(): void {
|
|
||||||
if (!this.cartDisabled()) this.cartClick.emit();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onLogoutClick(): void {
|
|
||||||
this.isUserDropdownOpen.set(false);
|
|
||||||
this.logoutClick.emit();
|
|
||||||
}
|
|
||||||
|
|
||||||
@HostListener('document:click', ['$event'])
|
|
||||||
protected onDocumentClick(event: MouseEvent): void {
|
|
||||||
if (event.target instanceof Node && !this.host.nativeElement.contains(event.target)) {
|
|
||||||
this.isUserDropdownOpen.set(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@HostListener('document:keydown.escape')
|
|
||||||
protected onEscapeKey(): void {
|
|
||||||
this.isUserDropdownOpen.set(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,192 +0,0 @@
|
|||||||
<header
|
|
||||||
class="store-layout__header"
|
|
||||||
[style.background-image]="backgroundImageUrl() ? 'url(' + backgroundImageUrl() + ')' : null"
|
|
||||||
>
|
|
||||||
<div class="store-layout__header-main">
|
|
||||||
<div class="container-xl px-3 px-md-4 py-3 py-lg-4">
|
|
||||||
<div class="row align-items-center gy-3 gy-md-0">
|
|
||||||
<div class="col-auto col-md-auto order-1 store-layout__brand-column">
|
|
||||||
<a
|
|
||||||
routerLink="/"
|
|
||||||
class="store-layout__brand-slot d-inline-flex align-items-center gap-3 text-decoration-none"
|
|
||||||
data-testid="store-header-brand-slot"
|
|
||||||
aria-label="Logo del comercio"
|
|
||||||
>
|
|
||||||
@if (logoUrl()) {
|
|
||||||
<img class="store-layout__brand-logo" [src]="logoUrl()" alt="Logo del comercio" />
|
|
||||||
} @else {
|
|
||||||
<div class="store-layout__brand-logo-shell" aria-hidden="true">
|
|
||||||
<span class="store-layout__brand-logo-skeleton"></span>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
@if (displaySeachBar()) {
|
|
||||||
<div class="col-12 px-0 d-md-none order-3">
|
|
||||||
<hr class="store-layout__mobile-separator" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="col-12 col-md order-4 order-md-2">
|
|
||||||
<div class="store-layout__search-wrapper ms-md-auto">
|
|
||||||
<div class="input-group store-layout__search" role="search">
|
|
||||||
<label class="visually-hidden" for="store-search-input">Buscar productos</label>
|
|
||||||
<input
|
|
||||||
id="store-search-input"
|
|
||||||
type="search"
|
|
||||||
class="form-control store-layout__search-input border-end-0 rounded-start"
|
|
||||||
placeholder="Buscar productos"
|
|
||||||
autocomplete="off"
|
|
||||||
[attr.aria-describedby]="showSearchError() ? 'store-search-error' : null"
|
|
||||||
[attr.aria-invalid]="showSearchError()"
|
|
||||||
[minlength]="minSearchLength"
|
|
||||||
[formControl]="searchControl"
|
|
||||||
(input)="clearSearchError()"
|
|
||||||
(keydown.enter)="submitSearch($event)"
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="btn store-layout__search-button border-start-0 rounded-end px-3"
|
|
||||||
aria-label="Buscar"
|
|
||||||
(click)="submitSearch()"
|
|
||||||
>
|
|
||||||
<i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
@if (showSearchError()) {
|
|
||||||
<p id="store-search-error" class="store-layout__search-error mb-0" role="alert">
|
|
||||||
Ingresá al menos {{ minSearchLength }} caracteres para buscar.
|
|
||||||
</p>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
<div
|
|
||||||
class="store-layout__actions-column col-auto col-md-auto order-2 order-md-3 ms-auto d-flex flex-row align-items-center justify-content-end gap-2 gap-md-3"
|
|
||||||
>
|
|
||||||
@if (ticketsMenu(); as menu) {
|
|
||||||
<app-button
|
|
||||||
variant="primary"
|
|
||||||
hostClass="store-layout__tickets-btn-host"
|
|
||||||
data-testid="store-header-tickets"
|
|
||||||
(click)="ticketsClick.emit()"
|
|
||||||
>
|
|
||||||
{{ menu.label }}
|
|
||||||
</app-button>
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (displayCart()) {
|
|
||||||
<app-cart-icon
|
|
||||||
[quantity]="cartDisabled() ? null : cartQuantity()"
|
|
||||||
[disabled]="cartDisabled()"
|
|
||||||
[ariaLabel]="
|
|
||||||
cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito de compras'
|
|
||||||
"
|
|
||||||
[title]="cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito'"
|
|
||||||
(click)="onCartClick()"
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
|
|
||||||
<div class="store-layout__user-menu d-none d-md-inline-flex position-relative">
|
|
||||||
<app-icon-button
|
|
||||||
variant="user"
|
|
||||||
ariaLabel="Mi cuenta"
|
|
||||||
ariaControls="store-user-dropdown"
|
|
||||||
[ariaExpanded]="isUserDropdownOpen()"
|
|
||||||
title="Mi cuenta"
|
|
||||||
(clicked)="toggleUserDropdown()"
|
|
||||||
/>
|
|
||||||
|
|
||||||
@if (isUserDropdownOpen()) {
|
|
||||||
<app-user-dropdown
|
|
||||||
id="store-user-dropdown"
|
|
||||||
[user]="user()"
|
|
||||||
[accountNavigationMenus]="accountNavigationMenus()"
|
|
||||||
(logoutClick)="onLogoutClick()"
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="store-layout__mobile-menu d-inline-flex d-md-none position-relative">
|
|
||||||
<app-icon-button
|
|
||||||
variant="bars"
|
|
||||||
ariaLabel="Menu"
|
|
||||||
ariaControls="store-mobile-menu"
|
|
||||||
[ariaExpanded]="isMobileMenuOpen()"
|
|
||||||
title="Menu"
|
|
||||||
(clicked)="toggleMobileMenu()"
|
|
||||||
/>
|
|
||||||
|
|
||||||
@if (isMobileMenuOpen()) {
|
|
||||||
<div
|
|
||||||
id="store-mobile-menu"
|
|
||||||
class="position-absolute end-0 bg-white rounded shadow mt-2 py-2 store-layout__mobile-dropdown-menu"
|
|
||||||
>
|
|
||||||
<a
|
|
||||||
class="dropdown-item d-flex align-items-center gap-2 px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
|
||||||
(click)="onMobileAccountClick()"
|
|
||||||
>
|
|
||||||
<i class="fa-regular fa-circle-user fa-lg"></i>
|
|
||||||
<span class="fw-medium">Mi cuenta</span>
|
|
||||||
</a>
|
|
||||||
|
|
||||||
@if (displayCategories()) {
|
|
||||||
<hr class="my-1 border-secondary opacity-25" />
|
|
||||||
|
|
||||||
@for (category of categories(); track category.id) {
|
|
||||||
<a
|
|
||||||
class="dropdown-item px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
|
||||||
(click)="onCategorySelect(category)"
|
|
||||||
>
|
|
||||||
<span class="fw-medium">{{ category.nombre }}</span>
|
|
||||||
</a>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="store-layout__categories d-none d-md-block">
|
|
||||||
<div class="container-xl h-100 px-3 px-md-4 d-flex align-items-center">
|
|
||||||
@if (displayCategories()) {
|
|
||||||
<div class="store-layout__category-menu">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="btn btn-link d-inline-flex align-items-center gap-2 px-0 py-3 text-uppercase fw-bold text-decoration-none store-layout__category-trigger"
|
|
||||||
aria-label="Categorias"
|
|
||||||
aria-controls="store-category-dropdown"
|
|
||||||
[attr.aria-expanded]="isCategoryDropdownOpen()"
|
|
||||||
(click)="toggleCategoryDropdown()"
|
|
||||||
>
|
|
||||||
<span>Categorias</span>
|
|
||||||
<i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<app-category-dropdown
|
|
||||||
id="store-category-dropdown"
|
|
||||||
[categories]="categories()"
|
|
||||||
[open]="isCategoryDropdownOpen()"
|
|
||||||
(categorySelect)="onCategorySelect($event)"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (checkoutRemainingTime(); as remainingTime) {
|
|
||||||
<div
|
|
||||||
class="store-layout__checkout-timer ms-auto d-none d-md-flex align-items-baseline gap-3"
|
|
||||||
role="timer"
|
|
||||||
aria-label="Tiempo restante de compra"
|
|
||||||
>
|
|
||||||
<span class="store-layout__checkout-timer-label">Tiempo restante de compra:</span>
|
|
||||||
<span class="store-layout__checkout-timer-value">{{ remainingTime }}</span>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
@@ -1,246 +0,0 @@
|
|||||||
.store-layout__header {
|
|
||||||
color: #ffffff;
|
|
||||||
background-color: var(--tenant-header-bg);
|
|
||||||
background-repeat: no-repeat;
|
|
||||||
background-position: center;
|
|
||||||
background-size: cover;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__header-main {
|
|
||||||
border-bottom: 1px solid var(--border-color);
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__categories {
|
|
||||||
height: 3.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__checkout-timer {
|
|
||||||
color: var(--tenant-primary);
|
|
||||||
font-weight: 700;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__checkout-timer-label {
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__checkout-timer-value {
|
|
||||||
font-size: 20px;
|
|
||||||
line-height: 1;
|
|
||||||
font-variant-numeric: tabular-nums;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-slot {
|
|
||||||
min-width: 150px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-column {
|
|
||||||
max-width: 12rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-logo-shell {
|
|
||||||
position: relative;
|
|
||||||
width: min(100%, 12rem);
|
|
||||||
height: 2.75rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-logo {
|
|
||||||
display: block;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
object-fit: contain;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-logo-skeleton {
|
|
||||||
display: block;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
border-radius: 0.75rem;
|
|
||||||
background: linear-gradient(
|
|
||||||
90deg,
|
|
||||||
rgba(255, 255, 255, 0.12) 0%,
|
|
||||||
rgba(255, 255, 255, 0.22) 50%,
|
|
||||||
rgba(255, 255, 255, 0.12) 100%
|
|
||||||
);
|
|
||||||
background-size: 200% 100%;
|
|
||||||
animation: store-header-logo-skeleton 1.2s ease-in-out infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-wrapper {
|
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (min-width: 768px) {
|
|
||||||
.store-layout__search-wrapper {
|
|
||||||
width: min(100%, 260px);
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__actions-column {
|
|
||||||
padding-left: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep .store-layout__tickets-btn-host {
|
|
||||||
flex: 0 0 clamp(8rem, 15vw, 13.5rem);
|
|
||||||
width: clamp(8rem, 15vw, 13.5rem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search {
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-error {
|
|
||||||
margin-top: 0.25rem;
|
|
||||||
font-size: 0.75rem;
|
|
||||||
line-height: 1.2;
|
|
||||||
color: var(--tenant-danger, #dc3545);
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-input {
|
|
||||||
color: #666666;
|
|
||||||
border-color: var(--border-color);
|
|
||||||
background-color: rgba(255, 255, 255, 0.96);
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-input::placeholder {
|
|
||||||
color: #666666;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-input:focus {
|
|
||||||
border-color: var(--border-color);
|
|
||||||
box-shadow: none;
|
|
||||||
outline: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-button {
|
|
||||||
color: #a0a0a0;
|
|
||||||
border-color: var(--border-color);
|
|
||||||
background-color: rgba(255, 255, 255, 0.96);
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-button:hover,
|
|
||||||
.store-layout__search-button:focus-visible {
|
|
||||||
color: #8a8a8a;
|
|
||||||
border-color: var(--border-color);
|
|
||||||
background-color: #ffffff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__action-button {
|
|
||||||
color: #a0a0a0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__action-button:hover,
|
|
||||||
.store-layout__action-button:focus-visible {
|
|
||||||
color: #8a8a8a;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__user-menu {
|
|
||||||
position: relative;
|
|
||||||
display: inline-flex;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__category-trigger {
|
|
||||||
font-size: 0.8rem;
|
|
||||||
letter-spacing: 0.02em;
|
|
||||||
color: #a0a0a0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__category-trigger:hover,
|
|
||||||
.store-layout__category-trigger:focus-visible {
|
|
||||||
color: #8a8a8a;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__category-menu {
|
|
||||||
position: relative;
|
|
||||||
display: inline-flex;
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__category-menu app-category-dropdown {
|
|
||||||
position: absolute;
|
|
||||||
z-index: 1050;
|
|
||||||
top: 100%;
|
|
||||||
left: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes store-header-logo-skeleton {
|
|
||||||
from {
|
|
||||||
background-position: 200% 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
to {
|
|
||||||
background-position: -200% 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 767.98px) {
|
|
||||||
.store-layout__brand-slot {
|
|
||||||
min-width: 0;
|
|
||||||
max-width: 150px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__actions-column {
|
|
||||||
flex: 1 1 auto;
|
|
||||||
width: auto;
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep .store-layout__tickets-btn-host {
|
|
||||||
flex: 1 1 0;
|
|
||||||
width: auto;
|
|
||||||
min-width: 0;
|
|
||||||
max-width: 50vw;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__mobile-separator {
|
|
||||||
border-color: var(--border-color);
|
|
||||||
opacity: 1;
|
|
||||||
margin: 0 -1rem;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 399.98px) {
|
|
||||||
.store-layout__brand-column {
|
|
||||||
flex: 1 1 0;
|
|
||||||
width: auto;
|
|
||||||
min-width: 0;
|
|
||||||
max-width: none;
|
|
||||||
padding-right: 0.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-slot {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 6.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__actions-column {
|
|
||||||
flex: 1 1 auto;
|
|
||||||
width: auto;
|
|
||||||
min-width: 0;
|
|
||||||
margin-left: 0 !important;
|
|
||||||
padding-left: 0.25rem;
|
|
||||||
gap: 0.25rem !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep .store-layout__tickets-btn-host .btn {
|
|
||||||
padding-inline: 0.75rem;
|
|
||||||
font-size: 0.875rem;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__mobile-dropdown-menu {
|
|
||||||
top: 100%;
|
|
||||||
min-width: 220px;
|
|
||||||
z-index: 1050;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__mobile-dropdown-item {
|
|
||||||
cursor: pointer;
|
|
||||||
color: #8a8a8a;
|
|
||||||
|
|
||||||
&:hover,
|
|
||||||
&:focus-visible {
|
|
||||||
color: #666666;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,172 +0,0 @@
|
|||||||
import {
|
|
||||||
Component,
|
|
||||||
computed,
|
|
||||||
ElementRef,
|
|
||||||
HostListener,
|
|
||||||
inject,
|
|
||||||
input,
|
|
||||||
output,
|
|
||||||
signal,
|
|
||||||
} from '@angular/core';
|
|
||||||
import { Router, RouterLink } from '@angular/router';
|
|
||||||
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
|
||||||
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
|
|
||||||
import { IconButtonComponent } from '../../../../shared/components/icon-button/icon-button.component';
|
|
||||||
import { UserDropdownComponent } from './user-dropdown/user-dropdown.component';
|
|
||||||
import { Menu } from '../../../services/tenant.interface';
|
|
||||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
|
||||||
import { ReactiveFormsModule, FormControl } from '@angular/forms';
|
|
||||||
import { Category } from '../../../services/tenant.interface';
|
|
||||||
import { CategoryDropdownComponent } from './category-dropdown/category-dropdown.component';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'app-standard-store-header',
|
|
||||||
imports: [
|
|
||||||
ButtonComponent,
|
|
||||||
CartIconComponent,
|
|
||||||
IconButtonComponent,
|
|
||||||
RouterLink,
|
|
||||||
ReactiveFormsModule,
|
|
||||||
UserDropdownComponent,
|
|
||||||
CategoryDropdownComponent,
|
|
||||||
],
|
|
||||||
templateUrl: './standard-store-header.component.html',
|
|
||||||
styleUrl: './standard-store-header.component.scss',
|
|
||||||
})
|
|
||||||
export class StandardStoreHeaderComponent {
|
|
||||||
private readonly elementRef = inject(ElementRef<HTMLElement>);
|
|
||||||
private readonly router = inject(Router);
|
|
||||||
|
|
||||||
readonly logoUrl = input<string | null>(null);
|
|
||||||
readonly backgroundImageUrl = input<string | null>(null);
|
|
||||||
readonly cartQuantity = input<number>(0);
|
|
||||||
readonly user = input<AuthUser | null>(null);
|
|
||||||
readonly isAuthenticated = input<boolean>(false);
|
|
||||||
readonly accountNavigationMenus = input<readonly Menu[]>([]);
|
|
||||||
readonly ticketsMenu = input<Menu | null>(null);
|
|
||||||
readonly categories = input<readonly Category[]>([]);
|
|
||||||
readonly displayCategories = input(true);
|
|
||||||
readonly displaySeachBar = input(true);
|
|
||||||
readonly displayCart = input(true);
|
|
||||||
readonly cartDisabled = input(false);
|
|
||||||
readonly checkoutRemainingSeconds = input<number | null>(null);
|
|
||||||
readonly cartClick = output<void>();
|
|
||||||
readonly ticketsClick = output<void>();
|
|
||||||
readonly loginClick = output<void>();
|
|
||||||
readonly logoutClick = output<void>();
|
|
||||||
readonly searchSubmit = output<string>();
|
|
||||||
readonly categorySelect = output<Category>();
|
|
||||||
|
|
||||||
protected readonly isUserDropdownOpen = signal(false);
|
|
||||||
protected readonly isCategoryDropdownOpen = signal(false);
|
|
||||||
protected readonly isMobileMenuOpen = signal(false);
|
|
||||||
protected readonly minSearchLength = 3;
|
|
||||||
protected readonly showSearchError = signal(false);
|
|
||||||
protected readonly searchControl = new FormControl('', { nonNullable: true });
|
|
||||||
protected readonly checkoutRemainingTime = computed(() => {
|
|
||||||
const remainingSeconds = this.checkoutRemainingSeconds();
|
|
||||||
|
|
||||||
if (remainingSeconds === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const minutes = Math.floor(remainingSeconds / 60);
|
|
||||||
const seconds = remainingSeconds % 60;
|
|
||||||
|
|
||||||
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
|
||||||
});
|
|
||||||
|
|
||||||
protected onCartClick(): void {
|
|
||||||
if (this.cartDisabled()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.cartClick.emit();
|
|
||||||
}
|
|
||||||
|
|
||||||
@HostListener('document:click', ['$event'])
|
|
||||||
protected onDocumentClick(event: MouseEvent): void {
|
|
||||||
if (!this.isUserDropdownOpen() && !this.isCategoryDropdownOpen() && !this.isMobileMenuOpen()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const target = event.target;
|
|
||||||
if (target instanceof Node && !this.elementRef.nativeElement.contains(target)) {
|
|
||||||
this.isUserDropdownOpen.set(false);
|
|
||||||
this.isCategoryDropdownOpen.set(false);
|
|
||||||
this.isMobileMenuOpen.set(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@HostListener('document:keydown.escape')
|
|
||||||
protected onEscapeKey(): void {
|
|
||||||
this.isUserDropdownOpen.set(false);
|
|
||||||
this.isCategoryDropdownOpen.set(false);
|
|
||||||
this.isMobileMenuOpen.set(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected toggleUserDropdown(): void {
|
|
||||||
if (!this.isAuthenticated()) {
|
|
||||||
this.loginClick.emit();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.isUserDropdownOpen.update((isOpen) => !isOpen);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onLoginClick(): void {
|
|
||||||
this.isUserDropdownOpen.set(false);
|
|
||||||
this.loginClick.emit();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onLogoutClick(): void {
|
|
||||||
this.isUserDropdownOpen.set(false);
|
|
||||||
this.logoutClick.emit();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected submitSearch(event?: Event): void {
|
|
||||||
event?.preventDefault();
|
|
||||||
|
|
||||||
const term = this.searchControl.value.trim();
|
|
||||||
|
|
||||||
if (term.length < this.minSearchLength) {
|
|
||||||
this.showSearchError.set(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.showSearchError.set(false);
|
|
||||||
this.searchSubmit.emit(term);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected clearSearchError(): void {
|
|
||||||
this.showSearchError.set(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected toggleCategoryDropdown(): void {
|
|
||||||
this.isCategoryDropdownOpen.update((isOpen) => !isOpen);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onCategorySelect(category: Category): void {
|
|
||||||
this.isCategoryDropdownOpen.set(false);
|
|
||||||
this.isMobileMenuOpen.set(false);
|
|
||||||
this.categorySelect.emit(category);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected toggleMobileMenu(): void {
|
|
||||||
this.isMobileMenuOpen.update((isOpen) => !isOpen);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onMobileAccountClick(): void {
|
|
||||||
this.isMobileMenuOpen.set(false);
|
|
||||||
if (!this.isAuthenticated()) {
|
|
||||||
this.loginClick.emit();
|
|
||||||
} else {
|
|
||||||
const menus = this.accountNavigationMenus();
|
|
||||||
if (menus.length > 0) {
|
|
||||||
this.router.navigate([menus[0].route]);
|
|
||||||
} else {
|
|
||||||
this.router.navigate(['/cuenta']);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,68 +1,181 @@
|
|||||||
@switch (headerType()) {
|
<header
|
||||||
@case ('immersive') {
|
class="store-layout__header"
|
||||||
<app-immersive-store-header
|
[style.background-image]="backgroundImageUrl() ? 'url(' + backgroundImageUrl() + ')' : null"
|
||||||
[logoUrl]="logoUrl()"
|
>
|
||||||
[backgroundImageUrl]="backgroundImageUrl()"
|
<div class="store-layout__header-main">
|
||||||
[heroContent]="heroContent()"
|
<div class="container-xl px-3 px-md-4 py-3 py-lg-4">
|
||||||
[carouselImages]="carouselImages()"
|
<div class="row align-items-center gy-3 gy-md-0">
|
||||||
[showHero]="showHero()"
|
<div class="col-auto col-md-auto order-1 store-layout__brand-column">
|
||||||
[cartQuantity]="cartQuantity()"
|
<a
|
||||||
[user]="user()"
|
routerLink="/"
|
||||||
[isAuthenticated]="isAuthenticated()"
|
class="store-layout__brand-slot d-inline-flex align-items-center gap-3 text-decoration-none"
|
||||||
[accountNavigationMenus]="accountNavigationMenus()"
|
data-testid="store-header-brand-slot"
|
||||||
[ticketsMenu]="ticketsMenu()"
|
aria-label="Logo del comercio"
|
||||||
[displaySearchBar]="displaySeachBar()"
|
>
|
||||||
[displayCart]="displayCart()"
|
@if (logoUrl()) {
|
||||||
[cartDisabled]="cartDisabled()"
|
<img class="store-layout__brand-logo" [src]="logoUrl()" alt="Logo del comercio" />
|
||||||
[checkoutRemainingSeconds]="checkoutRemainingSeconds()"
|
} @else {
|
||||||
(cartClick)="cartClick.emit()"
|
<div class="store-layout__brand-logo-shell" aria-hidden="true">
|
||||||
(ticketsClick)="ticketsClick.emit()"
|
<span class="store-layout__brand-logo-skeleton"></span>
|
||||||
(loginClick)="loginClick.emit()"
|
</div>
|
||||||
(logoutClick)="logoutClick.emit()"
|
|
||||||
(searchSubmit)="searchSubmit.emit($event)"
|
|
||||||
/>
|
|
||||||
}
|
}
|
||||||
@default {
|
</a>
|
||||||
<ng-container *ngTemplateOutlet="standardHeader" />
|
</div>
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
<ng-template #standardHeader>
|
@if (displaySeachBar()) {
|
||||||
<app-standard-store-header
|
<div class="col-12 px-0 d-md-none order-3">
|
||||||
[logoUrl]="logoUrl()"
|
<hr class="store-layout__mobile-separator" />
|
||||||
[backgroundImageUrl]="backgroundImageUrl()"
|
</div>
|
||||||
[cartQuantity]="cartQuantity()"
|
|
||||||
[user]="user()"
|
<div class="col-12 col-md order-4 order-md-2">
|
||||||
[isAuthenticated]="isAuthenticated()"
|
<div class="store-layout__search-wrapper ms-md-auto">
|
||||||
[accountNavigationMenus]="accountNavigationMenus()"
|
<div class="input-group store-layout__search" role="search">
|
||||||
[ticketsMenu]="ticketsMenu()"
|
<label class="visually-hidden" for="store-search-input">Buscar productos</label>
|
||||||
[categories]="categories()"
|
<input
|
||||||
[displayCategories]="displayCategories()"
|
id="store-search-input"
|
||||||
[displaySeachBar]="displaySeachBar()"
|
type="search"
|
||||||
[displayCart]="displayCart()"
|
class="form-control store-layout__search-input border-end-0 rounded-start"
|
||||||
[cartDisabled]="cartDisabled()"
|
placeholder="Buscar productos"
|
||||||
[checkoutRemainingSeconds]="checkoutRemainingSeconds()"
|
autocomplete="off"
|
||||||
(cartClick)="cartClick.emit()"
|
[attr.aria-describedby]="showSearchError() ? 'store-search-error' : null"
|
||||||
(ticketsClick)="ticketsClick.emit()"
|
[attr.aria-invalid]="showSearchError()"
|
||||||
(loginClick)="loginClick.emit()"
|
[minlength]="minSearchLength"
|
||||||
(logoutClick)="logoutClick.emit()"
|
[formControl]="searchControl"
|
||||||
(searchSubmit)="searchSubmit.emit($event)"
|
(input)="clearSearchError()"
|
||||||
(categorySelect)="categorySelect.emit($event)"
|
(keydown.enter)="submitSearch($event)"
|
||||||
/>
|
/>
|
||||||
</ng-template>
|
|
||||||
|
|
||||||
@if (headerType() === 'immersive' && displayCategories() && categories().length) {
|
|
||||||
<nav class="immersive-categories" aria-label="Categorías">
|
|
||||||
<div class="immersive-categories__list">
|
|
||||||
@for (category of categories(); track category.id) {
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="immersive-categories__item"
|
class="btn store-layout__search-button border-start-0 rounded-end px-3"
|
||||||
(click)="categorySelect.emit(category)"
|
aria-label="Buscar"
|
||||||
|
(click)="submitSearch()"
|
||||||
>
|
>
|
||||||
{{ category.nombre | uppercase }}
|
<i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
|
||||||
</button>
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (showSearchError()) {
|
||||||
|
<p id="store-search-error" class="store-layout__search-error mb-0" role="alert">
|
||||||
|
Ingresá al menos {{ minSearchLength }} caracteres para buscar.
|
||||||
|
</p>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
<div
|
||||||
|
class="store-layout__actions-column col-auto col-md-auto order-2 order-md-3 ms-auto d-flex flex-row align-items-center justify-content-end gap-2 gap-md-3"
|
||||||
|
>
|
||||||
|
@if (ticketsMenu(); as menu) {
|
||||||
|
<app-button
|
||||||
|
variant="primary"
|
||||||
|
hostClass="store-layout__tickets-btn-host"
|
||||||
|
data-testid="store-header-tickets"
|
||||||
|
(click)="ticketsClick.emit()"
|
||||||
|
>
|
||||||
|
{{ menu.label }}
|
||||||
|
</app-button>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (displayCart()) {
|
||||||
|
<app-cart-icon
|
||||||
|
[quantity]="cartDisabled() ? null : cartQuantity()"
|
||||||
|
[disabled]="cartDisabled()"
|
||||||
|
[ariaLabel]="
|
||||||
|
cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito de compras'
|
||||||
|
"
|
||||||
|
[title]="cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito'"
|
||||||
|
(click)="onCartClick()"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="store-layout__user-menu d-none d-md-inline-flex position-relative">
|
||||||
|
<app-icon-button
|
||||||
|
variant="user"
|
||||||
|
ariaLabel="Mi cuenta"
|
||||||
|
ariaControls="store-user-dropdown"
|
||||||
|
[ariaExpanded]="isUserDropdownOpen()"
|
||||||
|
title="Mi cuenta"
|
||||||
|
(clicked)="toggleUserDropdown()"
|
||||||
|
/>
|
||||||
|
|
||||||
|
@if (isUserDropdownOpen()) {
|
||||||
|
<app-user-dropdown
|
||||||
|
id="store-user-dropdown"
|
||||||
|
[user]="user()"
|
||||||
|
[accountNavigationMenus]="accountNavigationMenus()"
|
||||||
|
(logoutClick)="onLogoutClick()"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="store-layout__mobile-menu d-inline-flex d-md-none position-relative">
|
||||||
|
<app-icon-button
|
||||||
|
variant="bars"
|
||||||
|
ariaLabel="Menu"
|
||||||
|
ariaControls="store-mobile-menu"
|
||||||
|
[ariaExpanded]="isMobileMenuOpen()"
|
||||||
|
title="Menu"
|
||||||
|
(clicked)="toggleMobileMenu()"
|
||||||
|
/>
|
||||||
|
|
||||||
|
@if (isMobileMenuOpen()) {
|
||||||
|
<div
|
||||||
|
id="store-mobile-menu"
|
||||||
|
class="position-absolute end-0 bg-white rounded shadow mt-2 py-2 store-layout__mobile-dropdown-menu"
|
||||||
|
>
|
||||||
|
<a
|
||||||
|
class="dropdown-item d-flex align-items-center gap-2 px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
||||||
|
(click)="onMobileAccountClick()"
|
||||||
|
>
|
||||||
|
<i class="fa-regular fa-circle-user fa-lg"></i>
|
||||||
|
<span class="fw-medium">Mi cuenta</span>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
@if (displayCategories()) {
|
||||||
|
<hr class="my-1 border-secondary opacity-25" />
|
||||||
|
|
||||||
|
@for (category of categories(); track category.id) {
|
||||||
|
<a
|
||||||
|
class="dropdown-item px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
||||||
|
(click)="onCategorySelect(category)"
|
||||||
|
>
|
||||||
|
<span class="fw-medium">{{ category.nombre }}</span>
|
||||||
|
</a>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (displayCategories()) {
|
||||||
|
<div class="store-layout__categories d-none d-md-block">
|
||||||
|
<div class="container-xl px-3 px-md-4">
|
||||||
|
<div class="store-layout__category-menu">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn btn-link d-inline-flex align-items-center gap-2 px-0 py-3 text-uppercase fw-bold text-decoration-none store-layout__category-trigger"
|
||||||
|
aria-label="Categorias"
|
||||||
|
aria-controls="store-category-dropdown"
|
||||||
|
[attr.aria-expanded]="isCategoryDropdownOpen()"
|
||||||
|
(click)="toggleCategoryDropdown()"
|
||||||
|
>
|
||||||
|
<span>Categorias</span>
|
||||||
|
<i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<app-category-dropdown
|
||||||
|
id="store-category-dropdown"
|
||||||
|
[categories]="categories()"
|
||||||
|
[open]="isCategoryDropdownOpen()"
|
||||||
|
(categorySelect)="onCategorySelect($event)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</header>
|
||||||
|
|||||||
@@ -1,37 +1,226 @@
|
|||||||
:host {
|
.store-layout__header {
|
||||||
|
color: #ffffff;
|
||||||
|
background-color: var(--tenant-header-bg);
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
background-position: center;
|
||||||
|
background-size: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__header-main {
|
||||||
|
border-bottom: 1px solid var(--border-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__brand-slot {
|
||||||
|
min-width: 150px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__brand-column {
|
||||||
|
max-width: 12rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__brand-logo-shell {
|
||||||
|
position: relative;
|
||||||
|
width: min(100%, 12rem);
|
||||||
|
height: 2.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__brand-logo {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
|
||||||
|
|
||||||
.immersive-categories {
|
|
||||||
width: 100%;
|
width: 100%;
|
||||||
overflow-x: auto;
|
height: 100%;
|
||||||
background: #f5f5f5;
|
object-fit: contain;
|
||||||
}
|
}
|
||||||
|
|
||||||
.immersive-categories__list {
|
.store-layout__brand-logo-skeleton {
|
||||||
display: flex;
|
display: block;
|
||||||
align-items: center;
|
width: 100%;
|
||||||
justify-content: center;
|
height: 100%;
|
||||||
gap: clamp(1rem, 3vw, 2.5rem);
|
border-radius: 0.75rem;
|
||||||
width: max-content;
|
background: linear-gradient(
|
||||||
min-width: 100%;
|
90deg,
|
||||||
min-height: 3.5rem;
|
rgba(255, 255, 255, 0.12) 0%,
|
||||||
padding: 0.75rem 1rem;
|
rgba(255, 255, 255, 0.22) 50%,
|
||||||
|
rgba(255, 255, 255, 0.12) 100%
|
||||||
|
);
|
||||||
|
background-size: 200% 100%;
|
||||||
|
animation: store-header-logo-skeleton 1.2s ease-in-out infinite;
|
||||||
}
|
}
|
||||||
|
|
||||||
.immersive-categories__item {
|
.store-layout__search-wrapper {
|
||||||
flex: none;
|
width: 100%;
|
||||||
border: 0;
|
min-width: 0;
|
||||||
padding: 0;
|
}
|
||||||
background: transparent;
|
|
||||||
|
@media (min-width: 768px) {
|
||||||
|
.store-layout__search-wrapper {
|
||||||
|
width: min(100%, 260px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__actions-column {
|
||||||
|
padding-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .store-layout__tickets-btn-host {
|
||||||
|
flex: 0 0 clamp(8rem, 15vw, 13.5rem);
|
||||||
|
width: clamp(8rem, 15vw, 13.5rem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search-error {
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
line-height: 1.2;
|
||||||
|
color: var(--tenant-danger, #dc3545);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search-input {
|
||||||
color: #666666;
|
color: #666666;
|
||||||
font-size: 15px;
|
border-color: var(--border-color);
|
||||||
font-weight: 700;
|
background-color: rgba(255, 255, 255, 0.96);
|
||||||
white-space: nowrap;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.immersive-categories__item:hover,
|
.store-layout__search-input::placeholder {
|
||||||
.immersive-categories__item:focus-visible {
|
color: #666666;
|
||||||
text-decoration: underline;
|
}
|
||||||
|
|
||||||
|
.store-layout__search-input:focus {
|
||||||
|
border-color: var(--border-color);
|
||||||
|
box-shadow: none;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search-button {
|
||||||
|
color: #a0a0a0;
|
||||||
|
border-color: var(--border-color);
|
||||||
|
background-color: rgba(255, 255, 255, 0.96);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search-button:hover,
|
||||||
|
.store-layout__search-button:focus-visible {
|
||||||
|
color: #8a8a8a;
|
||||||
|
border-color: var(--border-color);
|
||||||
|
background-color: #ffffff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__action-button {
|
||||||
|
color: #a0a0a0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__action-button:hover,
|
||||||
|
.store-layout__action-button:focus-visible {
|
||||||
|
color: #8a8a8a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__user-menu {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__category-trigger {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
color: #a0a0a0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__category-trigger:hover,
|
||||||
|
.store-layout__category-trigger:focus-visible {
|
||||||
|
color: #8a8a8a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__category-menu {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__category-menu app-category-dropdown {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 1050;
|
||||||
|
top: 100%;
|
||||||
|
left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes store-header-logo-skeleton {
|
||||||
|
from {
|
||||||
|
background-position: 200% 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
background-position: -200% 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 767.98px) {
|
||||||
|
.store-layout__brand-slot {
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 150px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__actions-column {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
width: auto;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .store-layout__tickets-btn-host {
|
||||||
|
flex: 1 1 0;
|
||||||
|
width: auto;
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 50vw;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__mobile-separator {
|
||||||
|
border-color: var(--border-color);
|
||||||
|
opacity: 1;
|
||||||
|
margin: 0 -1rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 399.98px) {
|
||||||
|
.store-layout__brand-column {
|
||||||
|
flex: 1 1 0;
|
||||||
|
width: auto;
|
||||||
|
min-width: 0;
|
||||||
|
max-width: none;
|
||||||
|
padding-right: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__brand-slot {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 6.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__actions-column {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
width: auto;
|
||||||
|
min-width: 0;
|
||||||
|
margin-left: 0 !important;
|
||||||
|
padding-left: 0.25rem;
|
||||||
|
gap: 0.25rem !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .store-layout__tickets-btn-host .btn {
|
||||||
|
padding-inline: 0.75rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__mobile-dropdown-menu {
|
||||||
|
top: 100%;
|
||||||
|
min-width: 220px;
|
||||||
|
z-index: 1050;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__mobile-dropdown-item {
|
||||||
|
cursor: pointer;
|
||||||
|
color: #8a8a8a;
|
||||||
|
|
||||||
|
&:hover,
|
||||||
|
&:focus-visible {
|
||||||
|
color: #666666;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,35 @@
|
|||||||
import { NgTemplateOutlet, UpperCasePipe } from '@angular/common';
|
import { Component, ElementRef, HostListener, inject, input, output, signal } from '@angular/core';
|
||||||
import { Component, input, output } from '@angular/core';
|
import { Router, RouterLink } from '@angular/router';
|
||||||
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
||||||
import { Category, Menu, WebsiteExtras } from '../../../services/tenant.interface';
|
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
|
||||||
import { ImmersiveStoreHeaderComponent } from './immersive-store-header.component';
|
import { IconButtonComponent } from '../../../../shared/components/icon-button/icon-button.component';
|
||||||
import { StandardStoreHeaderComponent } from './standard-store-header.component';
|
import { UserDropdownComponent } from './user-dropdown/user-dropdown.component';
|
||||||
|
import { Menu } from '../../../services/tenant.interface';
|
||||||
export type StoreHeaderType = 'standard' | 'immersive';
|
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||||
|
import { ReactiveFormsModule, FormControl } from '@angular/forms';
|
||||||
|
import { Category } from '../../../services/tenant.interface';
|
||||||
|
import { CategoryDropdownComponent } from './category-dropdown/category-dropdown.component';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-store-header',
|
selector: 'app-store-header',
|
||||||
imports: [NgTemplateOutlet, UpperCasePipe, StandardStoreHeaderComponent, ImmersiveStoreHeaderComponent],
|
imports: [
|
||||||
|
ButtonComponent,
|
||||||
|
CartIconComponent,
|
||||||
|
IconButtonComponent,
|
||||||
|
RouterLink,
|
||||||
|
ReactiveFormsModule,
|
||||||
|
UserDropdownComponent,
|
||||||
|
CategoryDropdownComponent,
|
||||||
|
],
|
||||||
templateUrl: './store-header.component.html',
|
templateUrl: './store-header.component.html',
|
||||||
styleUrl: './store-header.component.scss',
|
styleUrl: './store-header.component.scss',
|
||||||
})
|
})
|
||||||
export class StoreHeaderComponent {
|
export class StoreHeaderComponent {
|
||||||
readonly headerType = input<StoreHeaderType>('standard');
|
private readonly elementRef = inject(ElementRef<HTMLElement>);
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
|
||||||
readonly logoUrl = input<string | null>(null);
|
readonly logoUrl = input<string | null>(null);
|
||||||
readonly backgroundImageUrl = input<string | null>(null);
|
readonly backgroundImageUrl = input<string | null>(null);
|
||||||
readonly heroContent = input<WebsiteExtras['immersiveHero']>(undefined);
|
|
||||||
readonly carouselImages = input<readonly string[]>([]);
|
|
||||||
readonly showHero = input(true);
|
|
||||||
readonly cartQuantity = input<number>(0);
|
readonly cartQuantity = input<number>(0);
|
||||||
readonly user = input<AuthUser | null>(null);
|
readonly user = input<AuthUser | null>(null);
|
||||||
readonly isAuthenticated = input<boolean>(false);
|
readonly isAuthenticated = input<boolean>(false);
|
||||||
@@ -30,12 +40,111 @@ export class StoreHeaderComponent {
|
|||||||
readonly displaySeachBar = input(true);
|
readonly displaySeachBar = input(true);
|
||||||
readonly displayCart = input(true);
|
readonly displayCart = input(true);
|
||||||
readonly cartDisabled = input(false);
|
readonly cartDisabled = input(false);
|
||||||
readonly checkoutRemainingSeconds = input<number | null>(null);
|
|
||||||
|
|
||||||
readonly cartClick = output<void>();
|
readonly cartClick = output<void>();
|
||||||
readonly ticketsClick = output<void>();
|
readonly ticketsClick = output<void>();
|
||||||
readonly loginClick = output<void>();
|
readonly loginClick = output<void>();
|
||||||
readonly logoutClick = output<void>();
|
readonly logoutClick = output<void>();
|
||||||
readonly searchSubmit = output<string>();
|
readonly searchSubmit = output<string>();
|
||||||
readonly categorySelect = output<Category>();
|
readonly categorySelect = output<Category>();
|
||||||
|
|
||||||
|
protected readonly isUserDropdownOpen = signal(false);
|
||||||
|
protected readonly isCategoryDropdownOpen = signal(false);
|
||||||
|
protected readonly isMobileMenuOpen = signal(false);
|
||||||
|
protected readonly minSearchLength = 3;
|
||||||
|
protected readonly showSearchError = signal(false);
|
||||||
|
protected readonly searchControl = new FormControl('', { nonNullable: true });
|
||||||
|
|
||||||
|
protected onCartClick(): void {
|
||||||
|
if (this.cartDisabled()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.cartClick.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
@HostListener('document:click', ['$event'])
|
||||||
|
protected onDocumentClick(event: MouseEvent): void {
|
||||||
|
if (!this.isUserDropdownOpen() && !this.isCategoryDropdownOpen() && !this.isMobileMenuOpen()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const target = event.target;
|
||||||
|
if (target instanceof Node && !this.elementRef.nativeElement.contains(target)) {
|
||||||
|
this.isUserDropdownOpen.set(false);
|
||||||
|
this.isCategoryDropdownOpen.set(false);
|
||||||
|
this.isMobileMenuOpen.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@HostListener('document:keydown.escape')
|
||||||
|
protected onEscapeKey(): void {
|
||||||
|
this.isUserDropdownOpen.set(false);
|
||||||
|
this.isCategoryDropdownOpen.set(false);
|
||||||
|
this.isMobileMenuOpen.set(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected toggleUserDropdown(): void {
|
||||||
|
if (!this.isAuthenticated()) {
|
||||||
|
this.loginClick.emit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isUserDropdownOpen.update((isOpen) => !isOpen);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onLoginClick(): void {
|
||||||
|
this.isUserDropdownOpen.set(false);
|
||||||
|
this.loginClick.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onLogoutClick(): void {
|
||||||
|
this.isUserDropdownOpen.set(false);
|
||||||
|
this.logoutClick.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected submitSearch(event?: Event): void {
|
||||||
|
event?.preventDefault();
|
||||||
|
|
||||||
|
const term = this.searchControl.value.trim();
|
||||||
|
|
||||||
|
if (term.length < this.minSearchLength) {
|
||||||
|
this.showSearchError.set(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.showSearchError.set(false);
|
||||||
|
this.searchSubmit.emit(term);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected clearSearchError(): void {
|
||||||
|
this.showSearchError.set(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected toggleCategoryDropdown(): void {
|
||||||
|
this.isCategoryDropdownOpen.update((isOpen) => !isOpen);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onCategorySelect(category: Category): void {
|
||||||
|
this.isCategoryDropdownOpen.set(false);
|
||||||
|
this.isMobileMenuOpen.set(false);
|
||||||
|
this.categorySelect.emit(category);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected toggleMobileMenu(): void {
|
||||||
|
this.isMobileMenuOpen.update((isOpen) => !isOpen);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onMobileAccountClick(): void {
|
||||||
|
this.isMobileMenuOpen.set(false);
|
||||||
|
if (!this.isAuthenticated()) {
|
||||||
|
this.loginClick.emit();
|
||||||
|
} else {
|
||||||
|
const menus = this.accountNavigationMenus();
|
||||||
|
if (menus.length > 0) {
|
||||||
|
this.router.navigate([menus[0].route]);
|
||||||
|
} else {
|
||||||
|
this.router.navigate(['/cuenta']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
<div class="store-layout d-flex flex-column flex-grow-1">
|
<div class="store-layout d-flex flex-column flex-grow-1">
|
||||||
<app-store-header
|
<app-store-header
|
||||||
ngSkipHydration
|
ngSkipHydration
|
||||||
[headerType]="tenant()?.header_type ?? 'standard'"
|
|
||||||
[heroContent]="tenant()?.extras?.immersiveHero"
|
|
||||||
[carouselImages]="tenant()?.extras?.immersiveHeroCarousel ?? []"
|
|
||||||
[showHero]="isHomeRoute()"
|
|
||||||
[cartQuantity]="cartQuantity()"
|
[cartQuantity]="cartQuantity()"
|
||||||
[logoUrl]="tenant()?.header_logo ?? null"
|
[logoUrl]="tenant()?.header_logo ?? null"
|
||||||
[backgroundImageUrl]="tenant()?.header_bg_image ?? null"
|
[backgroundImageUrl]="tenant()?.header_bg_image ?? null"
|
||||||
@@ -17,7 +13,6 @@
|
|||||||
[displaySeachBar]="tenant()?.display_seach_bar ?? true"
|
[displaySeachBar]="tenant()?.display_seach_bar ?? true"
|
||||||
[displayCart]="displayCart()"
|
[displayCart]="displayCart()"
|
||||||
[cartDisabled]="isCheckoutRoute()"
|
[cartDisabled]="isCheckoutRoute()"
|
||||||
[checkoutRemainingSeconds]="checkoutRemainingSeconds()"
|
|
||||||
(cartClick)="onCartClick()"
|
(cartClick)="onCartClick()"
|
||||||
(ticketsClick)="onTicketsClick()"
|
(ticketsClick)="onTicketsClick()"
|
||||||
(loginClick)="onLoginClick()"
|
(loginClick)="onLoginClick()"
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
:host {
|
:host {
|
||||||
display: flex;
|
display: flex;
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
min-height: 100dvh;
|
min-height: 100dvh;
|
||||||
background: #f5f5f5;
|
background: #f5f5f5;
|
||||||
color: #202020;
|
color: #202020;
|
||||||
@@ -9,8 +7,6 @@
|
|||||||
|
|
||||||
.store-layout {
|
.store-layout {
|
||||||
position: relative;
|
position: relative;
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__cart-overlay {
|
.store-layout__cart-overlay {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
|
||||||
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 {
|
import {
|
||||||
@@ -12,7 +11,7 @@ import {
|
|||||||
UrlSerializer,
|
UrlSerializer,
|
||||||
} from '@angular/router';
|
} from '@angular/router';
|
||||||
|
|
||||||
import { BehaviorSubject, of, throwError } 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';
|
||||||
@@ -23,11 +22,8 @@ import { AuthService } from '../../services/auth/auth.service';
|
|||||||
import { AuthUser } from '../../services/auth/auth.interfaces';
|
import { AuthUser } from '../../services/auth/auth.interfaces';
|
||||||
import { StoreLayoutComponent } from './store-layout.component';
|
import { StoreLayoutComponent } from './store-layout.component';
|
||||||
import { StoreHeaderComponent } from './store-header/store-header.component';
|
import { StoreHeaderComponent } from './store-header/store-header.component';
|
||||||
import { StandardStoreHeaderComponent } from './store-header/standard-store-header.component';
|
|
||||||
import { CheckoutService } from '../../services/checkout.service';
|
import { CheckoutService } from '../../services/checkout.service';
|
||||||
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
|
|
||||||
import { TenantUrlSerializer } from '../../services/tenant-url.serializer';
|
import { TenantUrlSerializer } from '../../services/tenant-url.serializer';
|
||||||
import { EventDateNoticeService } from '../../services/event-date-notice.service';
|
|
||||||
|
|
||||||
const tenant: Tenant = {
|
const tenant: Tenant = {
|
||||||
id: 1,
|
id: 1,
|
||||||
@@ -153,7 +149,6 @@ describe('StoreLayoutComponent', () => {
|
|||||||
let tenantState = signal<Tenant | null>(tenant);
|
let tenantState = signal<Tenant | null>(tenant);
|
||||||
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 checkoutRemainingSecondsState = signal<number | null>(null);
|
|
||||||
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
||||||
let queryParamMapState: BehaviorSubject<ParamMap>;
|
let queryParamMapState: BehaviorSubject<ParamMap>;
|
||||||
|
|
||||||
@@ -161,7 +156,6 @@ describe('StoreLayoutComponent', () => {
|
|||||||
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);
|
||||||
checkoutRemainingSecondsState = signal<number | null>(null);
|
|
||||||
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
||||||
const isAuthenticatedState = signal(false);
|
const isAuthenticatedState = signal(false);
|
||||||
checkoutServiceStub = {
|
checkoutServiceStub = {
|
||||||
@@ -213,25 +207,13 @@ describe('StoreLayoutComponent', () => {
|
|||||||
useValue: {
|
useValue: {
|
||||||
user: authUserState,
|
user: authUserState,
|
||||||
isAuthenticated: isAuthenticatedState,
|
isAuthenticated: isAuthenticatedState,
|
||||||
logout: vi.fn().mockReturnValue(of({ message: 'Sesión cerrada correctamente.' })),
|
logout: vi.fn().mockReturnValue(of(void 0)),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
provide: CheckoutService,
|
provide: CheckoutService,
|
||||||
useValue: checkoutServiceStub,
|
useValue: checkoutServiceStub,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
provide: CheckoutCountdownService,
|
|
||||||
useValue: {
|
|
||||||
remainingSeconds: checkoutRemainingSecondsState.asReadonly(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
provide: EventDateNoticeService,
|
|
||||||
useValue: {
|
|
||||||
claim: vi.fn().mockReturnValue(of({ data: [] })),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
});
|
});
|
||||||
@@ -248,81 +230,6 @@ 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('renders the immersive header with configured copy and carousel images', () => {
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
const element = fixture.nativeElement as HTMLElement;
|
|
||||||
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
|
||||||
expect(header.componentInstance.headerType()).toBe('standard');
|
|
||||||
expect(element.querySelector('app-standard-store-header')).not.toBeNull();
|
|
||||||
|
|
||||||
tenantState.set({
|
|
||||||
...tenant,
|
|
||||||
header_type: 'immersive',
|
|
||||||
extras: {
|
|
||||||
immersiveHero: {
|
|
||||||
eyebrow: 'Encendé tu',
|
|
||||||
title: 'experiencia',
|
|
||||||
description: 'Reservá tu entrada',
|
|
||||||
},
|
|
||||||
immersiveHeroCarousel: ['/first.jpg', '/second.jpg'],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(header.componentInstance.headerType()).toBe('immersive');
|
|
||||||
expect(element.querySelector('app-standard-store-header')).toBeNull();
|
|
||||||
expect(element.querySelector('app-immersive-store-header')).not.toBeNull();
|
|
||||||
expect(element.querySelector('.immersive-header__eyebrow')?.textContent).toContain(
|
|
||||||
'Encendé tu',
|
|
||||||
);
|
|
||||||
expect(element.querySelector('.immersive-header__title')?.textContent).toContain('experiencia');
|
|
||||||
expect(element.querySelector('.immersive-header__description')?.textContent).toContain(
|
|
||||||
'Reservá tu entrada',
|
|
||||||
);
|
|
||||||
expect(element.querySelectorAll('.continuous-carousel__set')).toHaveLength(2);
|
|
||||||
expect(element.querySelector('.continuous-carousel__image')?.getAttribute('src')).toBe(
|
|
||||||
'/first.jpg',
|
|
||||||
);
|
|
||||||
expect(element.querySelector('app-cart-icon')).not.toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows immersive categories below the header and navigates on selection', () => {
|
|
||||||
tenantState.set({
|
|
||||||
...tenant,
|
|
||||||
header_type: 'immersive',
|
|
||||||
display_categories: true,
|
|
||||||
categories: [{ id: 11, nombre: 'Música', subcategories: [] }],
|
|
||||||
});
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
const element = fixture.nativeElement as HTMLElement;
|
|
||||||
const header = element.querySelector('app-immersive-store-header header');
|
|
||||||
const categories = element.querySelector('app-store-header .immersive-categories');
|
|
||||||
const categoryButton = categories?.querySelector<HTMLButtonElement>('button');
|
|
||||||
|
|
||||||
expect(header).not.toBeNull();
|
|
||||||
expect(categories).not.toBeNull();
|
|
||||||
expect(header?.contains(categories)).toBe(false);
|
|
||||||
expect(categoryButton?.textContent?.trim()).toBe('MÚSICA');
|
|
||||||
|
|
||||||
const navigate = vi.spyOn(TestBed.inject(Router), 'navigate');
|
|
||||||
categoryButton?.click();
|
|
||||||
expect(navigate).toHaveBeenCalledWith(['/categoria', 11], { queryParams: { page: 1 } });
|
|
||||||
|
|
||||||
tenantState.set({
|
|
||||||
...tenant,
|
|
||||||
header_type: 'immersive',
|
|
||||||
display_categories: false,
|
|
||||||
categories: [{ id: 11, nombre: 'Música', subcategories: [] }],
|
|
||||||
});
|
|
||||||
fixture.detectChanges();
|
|
||||||
expect(element.querySelector('.immersive-categories')).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('opens the cart when requested through the openCart query parameter', () => {
|
it('opens the cart when requested through the openCart query parameter', () => {
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -339,7 +246,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => {
|
it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => {
|
||||||
tenantState.set({ ...tenant, base_path: 'fiesta' });
|
tenantState.set({ ...tenant, base_path: 'fiesta' });
|
||||||
const router = TestBed.inject(Router);
|
const router = TestBed.inject(Router);
|
||||||
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout/25');
|
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout?purchase=25');
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -363,22 +270,6 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(element.querySelector('.store-layout__cart-overlay')).toBeNull();
|
expect(element.querySelector('.store-layout__cart-overlay')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the synchronized countdown in the header whenever one is active', () => {
|
|
||||||
checkoutRemainingSecondsState.set(587);
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
const element = fixture.nativeElement as HTMLElement;
|
|
||||||
|
|
||||||
expect(element.querySelector('.store-layout__checkout-timer-label')?.textContent).toContain(
|
|
||||||
'Tiempo restante de compra:',
|
|
||||||
);
|
|
||||||
expect(element.querySelector('.store-layout__checkout-timer-value')?.textContent?.trim()).toBe(
|
|
||||||
'09:47',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
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,
|
||||||
@@ -403,7 +294,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(compiled.querySelector('app-cart')).toBeNull();
|
expect(compiled.querySelector('app-cart')).toBeNull();
|
||||||
expect(compiled.querySelector('.store-layout__cart-overlay')).toBeNull();
|
expect(compiled.querySelector('.store-layout__cart-overlay')).toBeNull();
|
||||||
|
|
||||||
const header = fixture.debugElement.query(By.directive(StandardStoreHeaderComponent));
|
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
||||||
(header.componentInstance as any).toggleMobileMenu();
|
(header.componentInstance as any).toggleMobileMenu();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
@@ -454,7 +345,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const header = fixture.debugElement.query(By.directive(StandardStoreHeaderComponent));
|
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
||||||
const searchButton = header.query(By.css('.store-layout__search-button'));
|
const searchButton = header.query(By.css('.store-layout__search-button'));
|
||||||
|
|
||||||
(header.componentInstance as any).searchControl.setValue(' zapatillas ');
|
(header.componentInstance as any).searchControl.setValue(' zapatillas ');
|
||||||
@@ -472,7 +363,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const header = fixture.debugElement.query(By.directive(StandardStoreHeaderComponent));
|
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
||||||
const input = header.query(By.css('#store-search-input'));
|
const input = header.query(By.css('#store-search-input'));
|
||||||
const keyboardEvent = {
|
const keyboardEvent = {
|
||||||
preventDefault: vi.fn(),
|
preventDefault: vi.fn(),
|
||||||
@@ -493,7 +384,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const header = fixture.debugElement.query(By.directive(StandardStoreHeaderComponent));
|
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
||||||
const input = header.query(By.css('#store-search-input'));
|
const input = header.query(By.css('#store-search-input'));
|
||||||
const searchButton = header.query(By.css('.store-layout__search-button'));
|
const searchButton = header.query(By.css('.store-layout__search-button'));
|
||||||
|
|
||||||
@@ -657,20 +548,6 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(authService.logout).toHaveBeenCalled();
|
expect(authService.logout).toHaveBeenCalled();
|
||||||
expect(cartService.clearCart).toHaveBeenCalled();
|
expect(cartService.clearCart).toHaveBeenCalled();
|
||||||
expect(router.navigate).toHaveBeenCalledWith(['/']);
|
expect(router.navigate).toHaveBeenCalledWith(['/']);
|
||||||
expect(TestBed.inject(ToastService).info).toHaveBeenCalledWith('Sesión cerrada correctamente.');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows a danger toast when logout fails', async () => {
|
|
||||||
const authService = TestBed.inject(AuthService);
|
|
||||||
const message = 'La sesión no pudo cerrarse en el servidor.';
|
|
||||||
(authService.logout as any).mockReturnValue(throwError(() => ({ error: { message } })));
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
await (fixture.componentInstance as any).onLogoutClick();
|
|
||||||
|
|
||||||
expect(TestBed.inject(ToastService).danger).toHaveBeenCalledWith(message);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('provides account actions from the footer', () => {
|
it('provides account actions from the footer', () => {
|
||||||
@@ -710,7 +587,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
const authService = TestBed.inject(AuthService);
|
const authService = TestBed.inject(AuthService);
|
||||||
const cartService = TestBed.inject(CartService);
|
const cartService = TestBed.inject(CartService);
|
||||||
const router = TestBed.inject(Router);
|
const router = TestBed.inject(Router);
|
||||||
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout/25');
|
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout?purchase=25');
|
||||||
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
@@ -797,44 +674,12 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
|
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
|
||||||
cart_id: 1,
|
cart_id: 1,
|
||||||
});
|
});
|
||||||
expect(router.navigate).toHaveBeenCalledWith(['/checkout', 55]);
|
expect(router.navigate).toHaveBeenCalledWith(['/checkout'], {
|
||||||
|
queryParams: { purchase: 55 },
|
||||||
|
});
|
||||||
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the backend message and refreshes the cart when its reservation expired', async () => {
|
|
||||||
const message = 'La reserva de stock venció. Usá el carrito activo para continuar.';
|
|
||||||
checkoutServiceStub.startCheckout.mockRejectedValue(
|
|
||||||
new HttpErrorResponse({
|
|
||||||
status: 422,
|
|
||||||
error: { code: 'stock_reservation.expired', message },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
cartState.set({
|
|
||||||
id: 1,
|
|
||||||
tenant_codigo: tenant.codigo,
|
|
||||||
status: 'active',
|
|
||||||
subtotal: '100.00',
|
|
||||||
items: [],
|
|
||||||
});
|
|
||||||
authUserState.set({
|
|
||||||
id: 7,
|
|
||||||
nombre_apellido: 'Juan Perez',
|
|
||||||
email: 'juan@example.com',
|
|
||||||
dni: '12345678',
|
|
||||||
telefono: '3415555555',
|
|
||||||
});
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
|
||||||
const loadCart = vi.spyOn(TestBed.inject(CartService), 'loadCart');
|
|
||||||
fixture.detectChanges();
|
|
||||||
loadCart.mockClear();
|
|
||||||
|
|
||||||
await (fixture.componentInstance as any).onCheckoutClick();
|
|
||||||
|
|
||||||
expect(TestBed.inject(ToastService).danger).toHaveBeenCalledWith(message);
|
|
||||||
expect(loadCart).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('allows modifying quantities directly in the regular cart without a toggle', () => {
|
it('allows modifying quantities directly in the regular cart without a toggle', () => {
|
||||||
cartState.set({
|
cartState.set({
|
||||||
id: 1,
|
id: 1,
|
||||||
|
|||||||
@@ -1,15 +1,4 @@
|
|||||||
import { isPlatformBrowser } from '@angular/common';
|
import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
|
||||||
import {
|
|
||||||
Component,
|
|
||||||
computed,
|
|
||||||
DestroyRef,
|
|
||||||
effect,
|
|
||||||
inject,
|
|
||||||
OnInit,
|
|
||||||
PLATFORM_ID,
|
|
||||||
signal,
|
|
||||||
} from '@angular/core';
|
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import {
|
import {
|
||||||
ActivatedRoute,
|
ActivatedRoute,
|
||||||
@@ -18,7 +7,7 @@ import {
|
|||||||
Router,
|
Router,
|
||||||
RouterOutlet,
|
RouterOutlet,
|
||||||
} from '@angular/router';
|
} from '@angular/router';
|
||||||
import { filter, firstValueFrom } from 'rxjs';
|
import { filter } from 'rxjs';
|
||||||
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';
|
||||||
@@ -28,16 +17,9 @@ import { ButtonComponent } from '../../../shared/components/button/button.compon
|
|||||||
import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface';
|
import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface';
|
||||||
import { AuthService } from '../../services/auth/auth.service';
|
import { AuthService } from '../../services/auth/auth.service';
|
||||||
import { findMenu } from '../../services/menu.utils';
|
import { findMenu } from '../../services/menu.utils';
|
||||||
import {
|
import { CheckoutService } from '../../services/checkout.service';
|
||||||
CheckoutService,
|
|
||||||
isExpiredStockReservationResponse,
|
|
||||||
} from '../../services/checkout.service';
|
|
||||||
import { ToastService } from '../../services/toast.service';
|
import { ToastService } from '../../services/toast.service';
|
||||||
import { Category } from '../../services/tenant.interface';
|
import { Category } from '../../services/tenant.interface';
|
||||||
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
|
|
||||||
import { EventDateNotice, EventDateNoticeService } from '../../services/event-date-notice.service';
|
|
||||||
import { ModalService } from '../../services/modal.service';
|
|
||||||
import { EventDateNoticeModalComponent } from '../../../shared/components/event-date-notice-modal/event-date-notice-modal.component';
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-store-layout',
|
selector: 'app-store-layout',
|
||||||
@@ -56,20 +38,13 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
private readonly cartService = inject(CartService);
|
private readonly cartService = inject(CartService);
|
||||||
private readonly authService = inject(AuthService);
|
private readonly authService = inject(AuthService);
|
||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
|
|
||||||
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 route = inject(ActivatedRoute);
|
||||||
private readonly destroyRef = inject(DestroyRef);
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
private readonly platformId = inject(PLATFORM_ID);
|
|
||||||
private readonly eventDateNoticeService = inject(EventDateNoticeService);
|
|
||||||
private readonly modalService = inject(ModalService);
|
|
||||||
private claimedNoticeUserId: number | null = null;
|
|
||||||
|
|
||||||
protected readonly isCartOpen = signal(false);
|
protected readonly isCartOpen = signal(false);
|
||||||
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url));
|
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url));
|
||||||
protected readonly isHomeRoute = signal(this.isHomeUrl(this.router.url));
|
|
||||||
protected readonly checkoutRemainingSeconds = this.checkoutCountdownService.remainingSeconds;
|
|
||||||
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 cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
|
||||||
@@ -86,27 +61,6 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
() => this.cartEditingPolicy()?.allow_update_variant ?? false,
|
() => this.cartEditingPolicy()?.allow_update_variant ?? false,
|
||||||
);
|
);
|
||||||
|
|
||||||
constructor() {
|
|
||||||
effect(() => {
|
|
||||||
const user = this.authService.user();
|
|
||||||
|
|
||||||
if (!isPlatformBrowser(this.platformId) || !user) {
|
|
||||||
this.claimedNoticeUserId = null;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.claimedNoticeUserId === user.id) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.claimedNoticeUserId = user.id;
|
|
||||||
this.eventDateNoticeService.claim().subscribe({
|
|
||||||
next: ({ data }) => void this.showEventDateNotices(data, user.id),
|
|
||||||
error: (error) => console.error('Error loading event date notices', error),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
protected readonly cartSubtotal = computed(() => {
|
protected readonly cartSubtotal = computed(() => {
|
||||||
const cart = this.cartService.cart();
|
const cart = this.cartService.cart();
|
||||||
return cart ? parseFloat(cart.subtotal) : 0;
|
return cart ? parseFloat(cart.subtotal) : 0;
|
||||||
@@ -211,7 +165,6 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
.subscribe((event) => {
|
.subscribe((event) => {
|
||||||
const isCheckoutRoute = this.isCheckoutUrl(event.urlAfterRedirects);
|
const isCheckoutRoute = this.isCheckoutUrl(event.urlAfterRedirects);
|
||||||
this.isCheckoutRoute.set(isCheckoutRoute);
|
this.isCheckoutRoute.set(isCheckoutRoute);
|
||||||
this.isHomeRoute.set(this.isHomeUrl(event.urlAfterRedirects));
|
|
||||||
|
|
||||||
if (isCheckoutRoute) {
|
if (isCheckoutRoute) {
|
||||||
this.isCartOpen.set(false);
|
this.isCartOpen.set(false);
|
||||||
@@ -235,11 +188,6 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
return primarySegments[0]?.path === 'checkout';
|
return primarySegments[0]?.path === 'checkout';
|
||||||
}
|
}
|
||||||
|
|
||||||
private isHomeUrl(url: string): boolean {
|
|
||||||
const primarySegments = this.router.parseUrl(url).root.children[PRIMARY_OUTLET]?.segments ?? [];
|
|
||||||
return primarySegments.length === 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onLoginClick(): void {
|
protected onLoginClick(): void {
|
||||||
void this.router.navigate(['/login']);
|
void this.router.navigate(['/login']);
|
||||||
}
|
}
|
||||||
@@ -252,28 +200,6 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
this.isCartOpen.update((isOpen) => !isOpen);
|
this.isCartOpen.update((isOpen) => !isOpen);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async showEventDateNotices(notices: EventDateNotice[], userId: number): Promise<void> {
|
|
||||||
for (const notice of notices) {
|
|
||||||
if (this.authService.user()?.id !== userId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const modalRef = this.modalService.open<EventDateNoticeModalComponent, void, EventDateNotice>(
|
|
||||||
EventDateNoticeModalComponent,
|
|
||||||
{
|
|
||||||
size: 'sm',
|
|
||||||
data: notice,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
await firstValueFrom(modalRef.afterClosed$);
|
|
||||||
|
|
||||||
if (modalRef.dismissReason() === 'replaced') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onSearch(term: string): void {
|
protected onSearch(term: string): void {
|
||||||
void this.router.navigate(['/buscar'], {
|
void this.router.navigate(['/buscar'], {
|
||||||
queryParams: { q: term, page: 1 },
|
queryParams: { q: term, page: 1 },
|
||||||
@@ -303,39 +229,23 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
const navigationSucceeded = await this.router.navigate(['/']);
|
const navigationSucceeded = await this.router.navigate(['/']);
|
||||||
|
|
||||||
if (!navigationSucceeded) {
|
if (!navigationSucceeded) {
|
||||||
this.toastService.danger('No se pudo cerrar la sesión. Intentá nuevamente.');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.authService.logout().subscribe({
|
this.authService.logout().subscribe({
|
||||||
next: ({ message }) => {
|
next: () => {
|
||||||
this.cartService.clearCart();
|
this.cartService.clearCart();
|
||||||
this.isCartOpen.set(false);
|
this.isCartOpen.set(false);
|
||||||
this.toastService.info(message || 'Sesión cerrada correctamente.');
|
|
||||||
|
|
||||||
if (!isLeavingCheckout) {
|
if (!isLeavingCheckout) {
|
||||||
void this.router.navigate(['/']);
|
void this.router.navigate(['/']);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error: (error: unknown) => {
|
error: (err) => console.error('Error logging out', err),
|
||||||
this.toastService.danger(this.resolveLogoutErrorMessage(error));
|
|
||||||
console.error('Error logging out', error);
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveLogoutErrorMessage(error: unknown): string {
|
|
||||||
const payload =
|
|
||||||
typeof error === 'object' && error !== null && 'error' in error
|
|
||||||
? (error as { error?: { message?: unknown } }).error
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
return typeof payload?.message === 'string' && payload.message.trim()
|
|
||||||
? payload.message
|
|
||||||
: 'No se pudo cerrar la sesión. Intentá nuevamente.';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected async onCheckoutClick(): Promise<void> {
|
protected async onCheckoutClick(): Promise<void> {
|
||||||
if (this.isCreatingPurchase()) {
|
if (this.isCreatingPurchase()) {
|
||||||
return;
|
return;
|
||||||
@@ -363,20 +273,12 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.isCartOpen.set(false);
|
this.isCartOpen.set(false);
|
||||||
await this.router.navigate(['/checkout', purchase.id]);
|
await this.router.navigate(['/checkout'], {
|
||||||
|
queryParams: { purchase: purchase.id },
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create cart purchase:', error);
|
console.error('Failed to create cart purchase:', error);
|
||||||
const message =
|
this.toastService.danger('No se pudo iniciar la compra.');
|
||||||
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
|
||||||
? error.error.message
|
|
||||||
: 'No se pudo iniciar la compra.';
|
|
||||||
this.toastService.danger(message);
|
|
||||||
|
|
||||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
|
||||||
this.cartService.loadCart(true).subscribe({
|
|
||||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
this.isCreatingPurchase.set(false);
|
this.isCreatingPurchase.set(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,12 +24,12 @@ describe('auth guards', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const result = TestBed.runInInjectionContext(() =>
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
authGuard(null as never, { url: '/checkout/25' } as never),
|
authGuard(null as never, { url: '/checkout?mode=direct' } as never),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(result instanceof UrlTree).toBe(true);
|
expect(result instanceof UrlTree).toBe(true);
|
||||||
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe(
|
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe(
|
||||||
'/login?returnUrl=%2Fcheckout%2F25',
|
'/login?returnUrl=%2Fcheckout%3Fmode%3Ddirect',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ describe('auth guards', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const result = TestBed.runInInjectionContext(() =>
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
authGuard(null as never, { url: '/checkout/25' } as never),
|
authGuard(null as never, { url: '/checkout' } as never),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
|
|||||||
@@ -33,10 +33,6 @@ export interface LoginResponse {
|
|||||||
user: AuthUser;
|
user: AuthUser;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LogoutResponse {
|
|
||||||
message: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface RegisterResponse {
|
export interface RegisterResponse {
|
||||||
message: string;
|
message: string;
|
||||||
data: AuthUser;
|
data: AuthUser;
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
AuthUser,
|
AuthUser,
|
||||||
LoginPayload,
|
LoginPayload,
|
||||||
LoginResponse,
|
LoginResponse,
|
||||||
LogoutResponse,
|
|
||||||
RegisterPayload,
|
RegisterPayload,
|
||||||
RegisterResponse,
|
RegisterResponse,
|
||||||
ResetPasswordPayload,
|
ResetPasswordPayload,
|
||||||
@@ -156,14 +155,14 @@ export class AuthService extends BaseApiService {
|
|||||||
.pipe(tap((user) => this.userState.set(user)));
|
.pipe(tap((user) => this.userState.set(user)));
|
||||||
}
|
}
|
||||||
|
|
||||||
logout(): Observable<LogoutResponse> {
|
logout(): Observable<void> {
|
||||||
if (!this.tokenState()) {
|
if (!this.tokenState()) {
|
||||||
this.clearSession();
|
this.clearSession();
|
||||||
return of({ message: 'Sesión cerrada correctamente.' });
|
return of(void 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.http
|
return this.http
|
||||||
.post<LogoutResponse>(`${environment.url}logout`, {})
|
.post<void>(`${environment.url}logout`, {})
|
||||||
.pipe(tap(() => this.clearSession()));
|
.pipe(tap(() => this.clearSession()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -83,20 +83,6 @@ describe('CartService', () => {
|
|||||||
req.flush({ data: mockCart });
|
req.flush({ data: mockCart });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('refreshes catalog availability only after the expired cart has been reloaded', () => {
|
|
||||||
const availabilityChanged = vi.fn();
|
|
||||||
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
|
||||||
|
|
||||||
service.loadCart(true).subscribe();
|
|
||||||
|
|
||||||
expect(availabilityChanged).not.toHaveBeenCalled();
|
|
||||||
const req = httpMock.expectOne('http://api.test/tenants/acme/cart');
|
|
||||||
req.flush({ data: mockCart });
|
|
||||||
|
|
||||||
expect(service.cart()).toEqual(mockCart);
|
|
||||||
expect(availabilityChanged).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('propagates a custom loading mode to the request context', () => {
|
it('propagates a custom loading mode to the request context', () => {
|
||||||
service.withCustomLoading().loadCart().subscribe();
|
service.withCustomLoading().loadCart().subscribe();
|
||||||
|
|
||||||
|
|||||||
@@ -34,19 +34,14 @@ export class CartService extends BaseApiService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
loadCart(refreshCatalogAvailability = false): Observable<Cart> {
|
loadCart(): Observable<Cart> {
|
||||||
return this.http
|
return this.http
|
||||||
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
|
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
map((response) => response.data),
|
map((response) => response.data),
|
||||||
tap((cart) => {
|
tap((cart) => this.cartState.set(cart)),
|
||||||
this.cartState.set(cart);
|
|
||||||
if (refreshCatalogAvailability) {
|
|
||||||
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
59
src/app/core/services/catalog/catalog-availability.spec.ts
Normal file
59
src/app/core/services/catalog/catalog-availability.spec.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { CatalogAvailability } from './catalog.interface';
|
||||||
|
import {
|
||||||
|
allowsCatalogAction,
|
||||||
|
combineCatalogAvailability,
|
||||||
|
createCatalogAvailability,
|
||||||
|
maximumCatalogQuantity,
|
||||||
|
} from './catalog-availability';
|
||||||
|
|
||||||
|
describe('catalog availability', () => {
|
||||||
|
it('represents hidden items without irrelevant actions or quantities', () => {
|
||||||
|
const availability = createCatalogAvailability(0);
|
||||||
|
|
||||||
|
expect(availability).toEqual({
|
||||||
|
state: 'hidden',
|
||||||
|
reasons: [
|
||||||
|
{
|
||||||
|
code: 'out_of_stock',
|
||||||
|
message: 'Este producto no tiene stock disponible.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(allowsCatalogAction(availability, 'buy_now')).toBe(false);
|
||||||
|
expect(maximumCatalogQuantity(availability)).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('intersects product and variant actions and quantities', () => {
|
||||||
|
const product: CatalogAvailability = {
|
||||||
|
state: 'visible',
|
||||||
|
maximum_quantity: 3,
|
||||||
|
allowed_actions: ['select_variant', 'change_quantity'],
|
||||||
|
reasons: [{ code: 'limited', message: 'Corregí la selección.' }],
|
||||||
|
};
|
||||||
|
const variant: CatalogAvailability = {
|
||||||
|
state: 'visible',
|
||||||
|
maximum_quantity: 2,
|
||||||
|
allowed_actions: ['change_quantity', 'add_to_cart'],
|
||||||
|
reasons: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(combineCatalogAvailability(product, variant)).toEqual({
|
||||||
|
state: 'visible',
|
||||||
|
maximum_quantity: 2,
|
||||||
|
allowed_actions: ['change_quantity'],
|
||||||
|
reasons: [{ code: 'limited', message: 'Corregí la selección.' }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lets a hidden decision win composition', () => {
|
||||||
|
const availability = combineCatalogAvailability(
|
||||||
|
createCatalogAvailability(5),
|
||||||
|
createCatalogAvailability(0),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(availability.state).toBe('hidden');
|
||||||
|
expect(allowsCatalogAction(availability, 'add_to_cart')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
80
src/app/core/services/catalog/catalog-availability.ts
Normal file
80
src/app/core/services/catalog/catalog-availability.ts
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import { CatalogAction, CatalogAvailability } from './catalog.interface';
|
||||||
|
|
||||||
|
const ALL_CATALOG_ACTIONS: CatalogAction[] = [
|
||||||
|
'select_variant',
|
||||||
|
'change_quantity',
|
||||||
|
'add_to_cart',
|
||||||
|
'buy_now',
|
||||||
|
];
|
||||||
|
|
||||||
|
export const AVAILABLE_CATALOG_AVAILABILITY: CatalogAvailability = {
|
||||||
|
state: 'visible',
|
||||||
|
maximum_quantity: null,
|
||||||
|
allowed_actions: ALL_CATALOG_ACTIONS,
|
||||||
|
reasons: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createCatalogAvailability(maximumQuantity: number | null): CatalogAvailability {
|
||||||
|
const unavailable = maximumQuantity === 0;
|
||||||
|
|
||||||
|
if (unavailable) {
|
||||||
|
return {
|
||||||
|
state: 'hidden',
|
||||||
|
reasons: [
|
||||||
|
{
|
||||||
|
code: 'out_of_stock',
|
||||||
|
message: 'Este producto no tiene stock disponible.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: 'visible',
|
||||||
|
maximum_quantity: maximumQuantity,
|
||||||
|
allowed_actions: [...ALL_CATALOG_ACTIONS],
|
||||||
|
reasons: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function primaryAvailabilityMessage(availability: CatalogAvailability): string | null {
|
||||||
|
return availability.reasons[0]?.message ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function allowsCatalogAction(
|
||||||
|
availability: CatalogAvailability,
|
||||||
|
action: CatalogAction,
|
||||||
|
): boolean {
|
||||||
|
return availability.state === 'visible' && availability.allowed_actions.includes(action);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function maximumCatalogQuantity(availability: CatalogAvailability): number | null {
|
||||||
|
return availability.state === 'visible' ? availability.maximum_quantity : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function combineCatalogAvailability(
|
||||||
|
product: CatalogAvailability,
|
||||||
|
variant?: CatalogAvailability | null,
|
||||||
|
): CatalogAvailability {
|
||||||
|
if (!variant) return product;
|
||||||
|
|
||||||
|
const reasons = [...product.reasons, ...variant.reasons];
|
||||||
|
if (product.state === 'hidden' || variant.state === 'hidden') {
|
||||||
|
return { state: 'hidden', reasons };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: 'visible',
|
||||||
|
maximum_quantity: minimumNullable(product.maximum_quantity, variant.maximum_quantity),
|
||||||
|
allowed_actions: product.allowed_actions.filter((action) =>
|
||||||
|
variant.allowed_actions.includes(action),
|
||||||
|
),
|
||||||
|
reasons,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function minimumNullable(left: number | null, right: number | null): number | null {
|
||||||
|
if (left === null) return right;
|
||||||
|
if (right === null) return left;
|
||||||
|
return Math.min(left, right);
|
||||||
|
}
|
||||||
@@ -49,6 +49,25 @@ export interface ProductAttribute {
|
|||||||
|
|
||||||
export type InventoryPolicy = 'tracked' | 'unlimited';
|
export type InventoryPolicy = 'tracked' | 'unlimited';
|
||||||
|
|
||||||
|
export interface CatalogRestriction {
|
||||||
|
code: 'out_of_stock' | 'user_quota_reached' | string;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CatalogAction = 'select_variant' | 'change_quantity' | 'add_to_cart' | 'buy_now';
|
||||||
|
|
||||||
|
export type CatalogAvailability =
|
||||||
|
| {
|
||||||
|
state: 'hidden';
|
||||||
|
reasons: CatalogRestriction[];
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
state: 'visible';
|
||||||
|
maximum_quantity: number | null;
|
||||||
|
allowed_actions: CatalogAction[];
|
||||||
|
reasons: CatalogRestriction[];
|
||||||
|
};
|
||||||
|
|
||||||
export interface CatalogVariantOption {
|
export interface CatalogVariantOption {
|
||||||
value: string;
|
value: string;
|
||||||
label: string;
|
label: string;
|
||||||
@@ -66,13 +85,12 @@ 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[];
|
||||||
maximum_addable_quantity?: number | null;
|
availability: CatalogAvailability;
|
||||||
unavailable_message?: string | 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;
|
||||||
effective_maximum_use_date?: string | null;
|
effective_maximum_use_date?: string | null;
|
||||||
values: Record<string, CatalogVariantValue>;
|
values: Record<string, string | string[]>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SelectedCatalogItemVariant extends CatalogItemVariant {
|
export interface SelectedCatalogItemVariant extends CatalogItemVariant {
|
||||||
@@ -99,7 +117,7 @@ export interface CatalogItemDetail {
|
|||||||
attributes: ProductAttribute[];
|
attributes: ProductAttribute[];
|
||||||
variants: CatalogItemVariant[];
|
variants: CatalogItemVariant[];
|
||||||
selected_variant?: SelectedCatalogItemVariant;
|
selected_variant?: SelectedCatalogItemVariant;
|
||||||
maximum_addable_quantity?: number | null;
|
availability: CatalogAvailability;
|
||||||
images?: string[];
|
images?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,8 +132,7 @@ export interface CatalogFeaturedItemVariant {
|
|||||||
id: number;
|
id: number;
|
||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string;
|
precio?: string;
|
||||||
maximum_addable_quantity?: number | null;
|
availability: CatalogAvailability;
|
||||||
unavailable_message?: string | null;
|
|
||||||
values: Record<string, CatalogVariantValue>;
|
values: Record<string, CatalogVariantValue>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,8 +164,7 @@ export interface CatalogFeaturedItem {
|
|||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio: number | string;
|
precio: number | string;
|
||||||
image?: string | null;
|
image?: string | null;
|
||||||
maximum_addable_quantity?: number | null;
|
availability: CatalogAvailability;
|
||||||
unavailable_message?: string | null;
|
|
||||||
variants?: CatalogFeaturedItemVariant[];
|
variants?: CatalogFeaturedItemVariant[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
CatalogItemDetail,
|
CatalogItemDetail,
|
||||||
CatalogVariantOptionsResponse,
|
CatalogVariantOptionsResponse,
|
||||||
CategoryItemsResponse,
|
CategoryItemsResponse,
|
||||||
|
Product,
|
||||||
} from './catalog.interface';
|
} from './catalog.interface';
|
||||||
|
|
||||||
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
|
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
|
||||||
@@ -32,6 +33,12 @@ export class CatalogService extends BaseApiService {
|
|||||||
return this.tenantService.getTenantApiUrl();
|
return this.tenantService.getTenantApiUrl();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getProductos(params?: ApiPaginationQueryParams): Observable<ApiPaginatedResponse<Product[]>> {
|
||||||
|
return this.http.get<ApiPaginatedResponse<Product[]>>(`${this.tenantApiUrl}/productos`, {
|
||||||
|
params: this.buildHttpParams(params),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
getCatalog(): Observable<CatalogFeaturedGroup[]> {
|
getCatalog(): Observable<CatalogFeaturedGroup[]> {
|
||||||
return this.http.get<CatalogFeaturedGroup[]>(`${this.tenantApiUrl}/catalog`);
|
return this.http.get<CatalogFeaturedGroup[]>(`${this.tenantApiUrl}/catalog`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
import { TestBed } from '@angular/core/testing';
|
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
||||||
|
|
||||||
import { CheckoutCountdownService } from './checkout-countdown.service';
|
|
||||||
|
|
||||||
describe('CheckoutCountdownService', () => {
|
|
||||||
let service: CheckoutCountdownService;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.useFakeTimers();
|
|
||||||
vi.setSystemTime(new Date('2026-08-27T12:00:00.000Z'));
|
|
||||||
TestBed.configureTestingModule({ providers: [CheckoutCountdownService] });
|
|
||||||
service = TestBed.inject(CheckoutCountdownService);
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
service.clear();
|
|
||||||
vi.useRealTimers();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('counts down from the checkout server timing without depending on the client clock', () => {
|
|
||||||
service.synchronize({
|
|
||||||
expires_at: '2026-08-27T15:10:00.000Z',
|
|
||||||
expires_in_seconds: 600,
|
|
||||||
server_time: '2026-08-27T15:00:00.000Z',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(service.remainingSeconds()).toBe(600);
|
|
||||||
|
|
||||||
vi.advanceTimersByTime(1_000);
|
|
||||||
|
|
||||||
expect(service.remainingSeconds()).toBe(599);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('recalculates against the deadline after a delayed browser interval', () => {
|
|
||||||
service.synchronize({
|
|
||||||
expires_at: null,
|
|
||||||
expires_in_seconds: 10,
|
|
||||||
server_time: '2026-08-27T15:00:00.000Z',
|
|
||||||
});
|
|
||||||
|
|
||||||
vi.setSystemTime(new Date('2026-08-27T12:00:07.000Z'));
|
|
||||||
vi.advanceTimersByTime(1_000);
|
|
||||||
|
|
||||||
expect(service.remainingSeconds()).toBe(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('clears the countdown when checkout has no expiration', () => {
|
|
||||||
service.synchronize({
|
|
||||||
expires_at: null,
|
|
||||||
expires_in_seconds: null,
|
|
||||||
server_time: '2026-08-27T15:00:00.000Z',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(service.remainingSeconds()).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps the active countdown when a partial checkout response omits timing fields', () => {
|
|
||||||
service.synchronize({
|
|
||||||
expires_at: null,
|
|
||||||
expires_in_seconds: 10,
|
|
||||||
server_time: '2026-08-27T15:00:00.000Z',
|
|
||||||
});
|
|
||||||
|
|
||||||
service.synchronize({});
|
|
||||||
|
|
||||||
expect(service.remainingSeconds()).toBe(10);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
import { Injectable, OnDestroy, signal } from '@angular/core';
|
|
||||||
|
|
||||||
export interface CheckoutTiming {
|
|
||||||
expires_at: string | null;
|
|
||||||
expires_in_seconds: number | null;
|
|
||||||
server_time: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Injectable({
|
|
||||||
providedIn: 'root',
|
|
||||||
})
|
|
||||||
export class CheckoutCountdownService implements OnDestroy {
|
|
||||||
private readonly remainingSecondsState = signal<number | null>(null);
|
|
||||||
private deadlineMs: number | null = null;
|
|
||||||
private intervalId: ReturnType<typeof setInterval> | null = null;
|
|
||||||
|
|
||||||
readonly remainingSeconds = this.remainingSecondsState.asReadonly();
|
|
||||||
|
|
||||||
synchronize(timing: Partial<CheckoutTiming>): void {
|
|
||||||
const remainingSeconds = this.resolveRemainingSeconds(timing);
|
|
||||||
|
|
||||||
if (remainingSeconds === undefined) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (remainingSeconds === null) {
|
|
||||||
this.clear();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.stopInterval();
|
|
||||||
this.deadlineMs = Date.now() + remainingSeconds * 1_000;
|
|
||||||
this.updateRemainingSeconds();
|
|
||||||
|
|
||||||
if (remainingSeconds > 0) {
|
|
||||||
this.intervalId = setInterval(() => this.updateRemainingSeconds(), 1_000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
clear(): void {
|
|
||||||
this.stopInterval();
|
|
||||||
this.deadlineMs = null;
|
|
||||||
this.remainingSecondsState.set(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
|
||||||
this.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
private resolveRemainingSeconds(timing: Partial<CheckoutTiming>): number | null | undefined {
|
|
||||||
if (timing.expires_at === null && timing.expires_in_seconds === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const expiresAt =
|
|
||||||
typeof timing.expires_at === 'string' ? Date.parse(timing.expires_at) : Number.NaN;
|
|
||||||
const serverTime =
|
|
||||||
typeof timing.server_time === 'string' ? Date.parse(timing.server_time) : Number.NaN;
|
|
||||||
|
|
||||||
if (Number.isFinite(expiresAt) && Number.isFinite(serverTime)) {
|
|
||||||
return Math.max(0, Math.ceil((expiresAt - serverTime) / 1_000));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
typeof timing.expires_in_seconds === 'number' &&
|
|
||||||
Number.isFinite(timing.expires_in_seconds)
|
|
||||||
) {
|
|
||||||
return Math.max(0, Math.ceil(timing.expires_in_seconds));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Number.isFinite(expiresAt)) {
|
|
||||||
return Math.max(0, Math.ceil((expiresAt - Date.now()) / 1_000));
|
|
||||||
}
|
|
||||||
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
private updateRemainingSeconds(): void {
|
|
||||||
if (this.deadlineMs === null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const remainingSeconds = Math.max(0, Math.ceil((this.deadlineMs - Date.now()) / 1_000));
|
|
||||||
this.remainingSecondsState.set(remainingSeconds);
|
|
||||||
|
|
||||||
if (remainingSeconds === 0) {
|
|
||||||
this.stopInterval();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private stopInterval(): void {
|
|
||||||
if (this.intervalId !== null) {
|
|
||||||
clearInterval(this.intervalId);
|
|
||||||
this.intervalId = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
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 { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
|
|
||||||
import { CheckoutService } from './checkout.service';
|
import { CheckoutService } from './checkout.service';
|
||||||
|
|
||||||
describe('CheckoutService', () => {
|
describe('CheckoutService', () => {
|
||||||
@@ -39,59 +38,4 @@ describe('CheckoutService', () => {
|
|||||||
|
|
||||||
await expect(purchasePromise).resolves.toMatchObject({ id: 55 });
|
await expect(purchasePromise).resolves.toMatchObject({ id: 55 });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('refreshes catalog availability when starting checkout fails', async () => {
|
|
||||||
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
|
||||||
const notifyAvailabilityChanged = vi.spyOn(
|
|
||||||
catalogAvailabilityService,
|
|
||||||
'notifyAvailabilityChanged',
|
|
||||||
);
|
|
||||||
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
|
|
||||||
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
|
||||||
|
|
||||||
request.flush(
|
|
||||||
{ message: 'No hay stock disponible.' },
|
|
||||||
{ status: 422, statusText: 'Unprocessable Entity' },
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(purchasePromise).rejects.toBeTruthy();
|
|
||||||
expect(notifyAvailabilityChanged).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('waits for the expired cart refresh before refreshing catalog availability', async () => {
|
|
||||||
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
|
||||||
const notifyAvailabilityChanged = vi.spyOn(
|
|
||||||
catalogAvailabilityService,
|
|
||||||
'notifyAvailabilityChanged',
|
|
||||||
);
|
|
||||||
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
|
|
||||||
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
|
||||||
|
|
||||||
request.flush(
|
|
||||||
{
|
|
||||||
code: 'stock_reservation.expired',
|
|
||||||
message: 'La reserva de stock venció.',
|
|
||||||
},
|
|
||||||
{ status: 422, statusText: 'Unprocessable Entity' },
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(purchasePromise).rejects.toBeTruthy();
|
|
||||||
expect(notifyAvailabilityChanged).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves checkout timing fields when completing a purchase', async () => {
|
|
||||||
const purchasePromise = service.completePurchase('desfile', 55);
|
|
||||||
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/55/complete`);
|
|
||||||
const response = {
|
|
||||||
status: 'pending_payment',
|
|
||||||
expires_at: '2026-08-26T20:00:00.000Z',
|
|
||||||
expires_in_seconds: 900,
|
|
||||||
server_time: '2026-08-26T19:45:00.000Z',
|
|
||||||
};
|
|
||||||
|
|
||||||
expect(request.request.method).toBe('POST');
|
|
||||||
request.flush({ data: response });
|
|
||||||
|
|
||||||
await expect(purchasePromise).resolves.toEqual(response);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { inject, Injectable } from '@angular/core';
|
import { Injectable } from '@angular/core';
|
||||||
import { firstValueFrom } from 'rxjs';
|
import { firstValueFrom } from 'rxjs';
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
import { ApiPaginatedResponse } from './api-paginated-response.interface';
|
import { ApiPaginatedResponse } from './api-paginated-response.interface';
|
||||||
import { ApiPaginationQueryParams } from './api-pagination-query-params.interface';
|
import { ApiPaginationQueryParams } from './api-pagination-query-params.interface';
|
||||||
import { BaseApiService } from './base-api.service';
|
import { BaseApiService } from './base-api.service';
|
||||||
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
|
|
||||||
|
|
||||||
export interface UpdatePurchaseCustomerPayload {
|
export interface UpdatePurchaseCustomerPayload {
|
||||||
dni: string;
|
dni: string;
|
||||||
@@ -46,21 +45,6 @@ export function isInsufficientStockResponse(value: unknown): value is Insufficie
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ExpiredStockReservationResponse {
|
|
||||||
code: 'stock_reservation.expired';
|
|
||||||
message: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isExpiredStockReservationResponse(
|
|
||||||
value: unknown,
|
|
||||||
): value is ExpiredStockReservationResponse {
|
|
||||||
return (
|
|
||||||
typeof value === 'object' &&
|
|
||||||
value !== null &&
|
|
||||||
(value as Partial<ExpiredStockReservationResponse>).code === 'stock_reservation.expired'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export type StartCheckoutPayload =
|
export type StartCheckoutPayload =
|
||||||
| {
|
| {
|
||||||
cart_id: number;
|
cart_id: number;
|
||||||
@@ -71,32 +55,6 @@ export type StartCheckoutPayload =
|
|||||||
|
|
||||||
export interface PurchaseStatusResponse {
|
export interface PurchaseStatusResponse {
|
||||||
status: string | null;
|
status: string | null;
|
||||||
expires_at: string | null;
|
|
||||||
expires_in_seconds: number | null;
|
|
||||||
server_time: string;
|
|
||||||
payment_verification?: PurchasePaymentVerificationResponse;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type PurchasePaymentCandidateReason =
|
|
||||||
| 'ambiguous_exact_match'
|
|
||||||
| 'exact_dni_near_amount'
|
|
||||||
| 'exact_amount_near_dni';
|
|
||||||
|
|
||||||
export interface PurchasePaymentCandidatePrimaryResponse {
|
|
||||||
reason: PurchasePaymentCandidateReason;
|
|
||||||
dni_distance: number | null;
|
|
||||||
payment_amount: string;
|
|
||||||
purchase_amount: string;
|
|
||||||
amount_difference: string;
|
|
||||||
confidence: 'exact' | 'high' | 'medium';
|
|
||||||
detected_at: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PurchasePaymentVerificationResponse {
|
|
||||||
status: 'pending' | 'candidate';
|
|
||||||
candidate_count: number;
|
|
||||||
primary: PurchasePaymentCandidatePrimaryResponse | null;
|
|
||||||
reasons: PurchasePaymentCandidateReason[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
|
export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
|
||||||
@@ -133,6 +91,7 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
|||||||
user_id: number;
|
user_id: number;
|
||||||
created_at: string | null;
|
created_at: string | null;
|
||||||
payment_method: string | null;
|
payment_method: string | null;
|
||||||
|
expires_at: string | null;
|
||||||
dni: string | null;
|
dni: string | null;
|
||||||
transfer_payer_dni: string | null;
|
transfer_payer_dni: string | null;
|
||||||
telefono: string | null;
|
telefono: string | null;
|
||||||
@@ -150,13 +109,10 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
|||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class CheckoutService extends BaseApiService {
|
export class CheckoutService extends BaseApiService {
|
||||||
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
|
|
||||||
|
|
||||||
async startCheckout(
|
async startCheckout(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
payload: StartCheckoutPayload,
|
payload: StartCheckoutPayload,
|
||||||
): Promise<PurchaseDetailResponse> {
|
): Promise<PurchaseDetailResponse> {
|
||||||
try {
|
|
||||||
const response = await firstValueFrom(
|
const response = await firstValueFrom(
|
||||||
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||||
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
|
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
|
||||||
@@ -171,13 +127,6 @@ export class CheckoutService extends BaseApiService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return purchase;
|
return purchase;
|
||||||
} catch (error) {
|
|
||||||
const responseBody = (error as { error?: unknown } | null)?.error;
|
|
||||||
if (!isExpiredStockReservationResponse(responseBody)) {
|
|
||||||
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async generatePaymentIntent(
|
async generatePaymentIntent(
|
||||||
@@ -222,6 +171,25 @@ export class CheckoutService extends BaseApiService {
|
|||||||
return purchase;
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async completePurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||||
|
const response = await firstValueFrom(
|
||||||
|
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
|
||||||
|
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/complete`,
|
||||||
|
{},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const purchase = this.extractResponseData<PurchaseStatusResponse>(response);
|
||||||
|
|
||||||
|
if (!purchase) {
|
||||||
|
throw new Error('Error al finalizar la compra.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: purchase.status ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
async submitPurchaseForReview(
|
async submitPurchaseForReview(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
@@ -238,7 +206,7 @@ export class CheckoutService extends BaseApiService {
|
|||||||
throw new Error('Error al enviar la compra a revisi\u00f3n.');
|
throw new Error('Error al enviar la compra a revisi\u00f3n.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return purchase;
|
return { status: purchase.status ?? null };
|
||||||
}
|
}
|
||||||
|
|
||||||
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||||
@@ -254,7 +222,7 @@ export class CheckoutService extends BaseApiService {
|
|||||||
throw new Error('Error al cancelar la compra.');
|
throw new Error('Error al cancelar la compra.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return purchase;
|
return { status: purchase.status ?? null };
|
||||||
}
|
}
|
||||||
|
|
||||||
async getPurchases(
|
async getPurchases(
|
||||||
|
|||||||
@@ -1,59 +0,0 @@
|
|||||||
import { provideHttpClient } from '@angular/common/http';
|
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
|
||||||
import { TestBed } from '@angular/core/testing';
|
|
||||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
|
||||||
import { EventDateNotice, EventDateNoticeService } from './event-date-notice.service';
|
|
||||||
import { ApiResponse } from './api-response.interface';
|
|
||||||
import { TenantService } from './tenant.service';
|
|
||||||
|
|
||||||
describe('EventDateNoticeService', () => {
|
|
||||||
let service: EventDateNoticeService;
|
|
||||||
let httpMock: HttpTestingController;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
providers: [
|
|
||||||
EventDateNoticeService,
|
|
||||||
provideHttpClient(),
|
|
||||||
provideHttpClientTesting(),
|
|
||||||
{
|
|
||||||
provide: TenantService,
|
|
||||||
useValue: { getTenant: () => ({ codigo: 'festival' }) },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
service = TestBed.inject(EventDateNoticeService);
|
|
||||||
httpMock = TestBed.inject(HttpTestingController);
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => httpMock.verify());
|
|
||||||
|
|
||||||
it('claims pending notices for the active tenant', () => {
|
|
||||||
const response = {
|
|
||||||
data: [
|
|
||||||
{
|
|
||||||
type: 'suspended' as const,
|
|
||||||
change_ids: [10],
|
|
||||||
title: 'FECHA CANCELADA!',
|
|
||||||
message: [{ text: 'La fecha fue cancelada.', bold: false }],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
let result: ApiResponse<EventDateNotice[]> | undefined;
|
|
||||||
|
|
||||||
service.claim().subscribe((value) => (result = value));
|
|
||||||
|
|
||||||
const request = httpMock.expectOne(
|
|
||||||
`${environment.url}tenants/festival/event-date-notices/claim`,
|
|
||||||
);
|
|
||||||
expect(request.request.method).toBe('POST');
|
|
||||||
expect(request.request.body).toEqual({});
|
|
||||||
|
|
||||||
request.flush(response);
|
|
||||||
|
|
||||||
expect(result).toEqual(response);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
import { inject, Injectable } from '@angular/core';
|
|
||||||
import { Observable } from 'rxjs';
|
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
|
||||||
import { ApiResponse } from './api-response.interface';
|
|
||||||
import { BaseApiService } from './base-api.service';
|
|
||||||
import { TenantService } from './tenant.service';
|
|
||||||
|
|
||||||
export type EventDateNoticeType = 'rescheduled' | 'suspended';
|
|
||||||
|
|
||||||
export interface EventDateNoticeSegment {
|
|
||||||
text: string;
|
|
||||||
bold: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface EventDateNotice {
|
|
||||||
type: EventDateNoticeType;
|
|
||||||
change_ids: number[];
|
|
||||||
title: string;
|
|
||||||
message: EventDateNoticeSegment[];
|
|
||||||
}
|
|
||||||
|
|
||||||
@Injectable({ providedIn: 'root' })
|
|
||||||
export class EventDateNoticeService extends BaseApiService {
|
|
||||||
private readonly tenantService = inject(TenantService);
|
|
||||||
|
|
||||||
claim(): Observable<ApiResponse<EventDateNotice[]>> {
|
|
||||||
const tenant = this.tenantService.getTenant();
|
|
||||||
|
|
||||||
if (!tenant) {
|
|
||||||
throw new Error('No se pudo resolver el tenant activo.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.withoutLoading().http.post<ApiResponse<EventDateNotice[]>>(
|
|
||||||
`${environment.url}tenants/${tenant.codigo}/event-date-notices/claim`,
|
|
||||||
{},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
import { ApiPaginatedResponse } from '../api-paginated-response.interface';
|
|
||||||
|
|
||||||
export interface StoreEvent {
|
|
||||||
id: number;
|
|
||||||
title: string;
|
|
||||||
subtitle: string | null;
|
|
||||||
description: string | null;
|
|
||||||
location: string | null;
|
|
||||||
exact_location: { latitude: number; longitude: number } | null;
|
|
||||||
date_text: string | null;
|
|
||||||
start_time?: string | null;
|
|
||||||
starts_at?: string | null;
|
|
||||||
dates?: { id: number; date: string; time_start: string }[];
|
|
||||||
social_media?: { code: string; url: string }[];
|
|
||||||
attachment_id: number | null;
|
|
||||||
image: string | null;
|
|
||||||
catalog_items?: {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
description: string | null;
|
|
||||||
price: string;
|
|
||||||
image: string | null;
|
|
||||||
requires_selection: boolean;
|
|
||||||
maximum_quantity: number | null;
|
|
||||||
variants: {
|
|
||||||
id: number;
|
|
||||||
price: string;
|
|
||||||
event_date_ids: number[];
|
|
||||||
maximum_quantity: number | null;
|
|
||||||
}[];
|
|
||||||
}[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export type StoreEventPage = ApiPaginatedResponse<StoreEvent[]>;
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
import { inject, Injectable } from '@angular/core';
|
|
||||||
import { Observable } from 'rxjs';
|
|
||||||
|
|
||||||
import { BaseApiService } from '../base-api.service';
|
|
||||||
import { ApiResponse } from '../api-response.interface';
|
|
||||||
import { TenantService } from '../tenant.service';
|
|
||||||
import { StoreEvent, StoreEventPage } from './event.interface';
|
|
||||||
|
|
||||||
@Injectable({ providedIn: 'root' })
|
|
||||||
export class EventService extends BaseApiService {
|
|
||||||
private readonly tenantService = inject(TenantService);
|
|
||||||
|
|
||||||
list(page: number, query = ''): Observable<StoreEventPage> {
|
|
||||||
return this.http.get<StoreEventPage>(`${this.tenantService.getTenantApiUrl()}/events`, {
|
|
||||||
params: { page, ...(query ? { q: query } : {}) },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
get(id: number): Observable<ApiResponse<StoreEvent>> {
|
|
||||||
return this.http.get<ApiResponse<StoreEvent>>(
|
|
||||||
`${this.tenantService.getTenantApiUrl()}/events/${id}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,6 @@ import { firstValueFrom } from 'rxjs';
|
|||||||
|
|
||||||
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
||||||
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
||||||
import { ImageModalComponent } from '../../shared/components/image-modal/image-modal.component';
|
|
||||||
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
||||||
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
||||||
import { MODAL_DATA, ModalRef, ModalService } from './modal.service';
|
import { MODAL_DATA, ModalRef, ModalService } from './modal.service';
|
||||||
@@ -80,21 +79,6 @@ describe('ModalService', () => {
|
|||||||
expect(ref.dismissReason()).toBeNull();
|
expect(ref.dismissReason()).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('keeps a modal opened synchronously from an afterClosed subscriber', () => {
|
|
||||||
const firstRef = service.open(FirstTestModalComponent);
|
|
||||||
let secondRef: ModalRef | undefined;
|
|
||||||
|
|
||||||
firstRef.afterClosed$.subscribe(() => {
|
|
||||||
secondRef = service.open(SecondTestModalComponent);
|
|
||||||
});
|
|
||||||
|
|
||||||
firstRef.close();
|
|
||||||
|
|
||||||
expect(secondRef).toBeDefined();
|
|
||||||
expect(service.activeModal()?.ref).toBe(secondRef);
|
|
||||||
expect(service.activeModal()?.component).toBe(SecondTestModalComponent);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('tracks dismiss reasons when closing programmatically', () => {
|
it('tracks dismiss reasons when closing programmatically', () => {
|
||||||
const ref = service.open(FirstTestModalComponent);
|
const ref = service.open(FirstTestModalComponent);
|
||||||
const closedSpy = vi.fn();
|
const closedSpy = vi.fn();
|
||||||
@@ -137,7 +121,7 @@ describe('ModalService', () => {
|
|||||||
it('opens the standard confirm modal with default labels', () => {
|
it('opens the standard confirm modal with default labels', () => {
|
||||||
const result$ = service.openConfirm({
|
const result$ = service.openConfirm({
|
||||||
title: 'Confirmar compra',
|
title: 'Confirmar compra',
|
||||||
description: 'Esto confirmara la compra actual.',
|
content: 'Esto confirmara la compra actual.',
|
||||||
});
|
});
|
||||||
|
|
||||||
const activeModal = service.activeModal();
|
const activeModal = service.activeModal();
|
||||||
@@ -145,9 +129,9 @@ describe('ModalService', () => {
|
|||||||
expect(activeModal?.component).toBe(ConfirmModalComponent);
|
expect(activeModal?.component).toBe(ConfirmModalComponent);
|
||||||
expect(result$).toBeDefined();
|
expect(result$).toBeDefined();
|
||||||
expect(activeModal?.config).toEqual({
|
expect(activeModal?.config).toEqual({
|
||||||
data: {
|
|
||||||
title: 'Confirmar compra',
|
title: 'Confirmar compra',
|
||||||
description: 'Esto confirmara la compra actual.',
|
data: {
|
||||||
|
content: 'Esto confirmara la compra actual.',
|
||||||
confirmLabel: 'Confirmar',
|
confirmLabel: 'Confirmar',
|
||||||
cancelLabel: 'Cancelar',
|
cancelLabel: 'Cancelar',
|
||||||
},
|
},
|
||||||
@@ -161,7 +145,7 @@ describe('ModalService', () => {
|
|||||||
it('maps the confirm modal close result to true', async () => {
|
it('maps the confirm modal close result to true', async () => {
|
||||||
const result$ = service.openConfirm({
|
const result$ = service.openConfirm({
|
||||||
title: 'Confirmar compra',
|
title: 'Confirmar compra',
|
||||||
description: 'Esto confirmara la compra actual.',
|
content: 'Esto confirmara la compra actual.',
|
||||||
});
|
});
|
||||||
const activeModal = service.activeModal();
|
const activeModal = service.activeModal();
|
||||||
const resultPromise = firstValueFrom(result$);
|
const resultPromise = firstValueFrom(result$);
|
||||||
@@ -174,7 +158,7 @@ describe('ModalService', () => {
|
|||||||
it('maps dismissing a confirm modal to false', async () => {
|
it('maps dismissing a confirm modal to false', async () => {
|
||||||
const result$ = service.openConfirmDelete({
|
const result$ = service.openConfirmDelete({
|
||||||
title: 'Eliminar producto',
|
title: 'Eliminar producto',
|
||||||
description: 'Se eliminara el producto.',
|
content: 'Se eliminara el producto.',
|
||||||
});
|
});
|
||||||
const activeModal = service.activeModal();
|
const activeModal = service.activeModal();
|
||||||
const resultPromise = firstValueFrom(result$);
|
const resultPromise = firstValueFrom(result$);
|
||||||
@@ -189,7 +173,7 @@ describe('ModalService', () => {
|
|||||||
it('opens the delete confirm modal preserving modal overrides', () => {
|
it('opens the delete confirm modal preserving modal overrides', () => {
|
||||||
service.openConfirmDelete({
|
service.openConfirmDelete({
|
||||||
title: 'Eliminar producto',
|
title: 'Eliminar producto',
|
||||||
description: 'Se eliminara el producto.',
|
content: 'Se eliminara el producto.',
|
||||||
confirmLabel: 'Eliminar',
|
confirmLabel: 'Eliminar',
|
||||||
cancelLabel: 'Conservar',
|
cancelLabel: 'Conservar',
|
||||||
size: 'lg',
|
size: 'lg',
|
||||||
@@ -202,9 +186,9 @@ describe('ModalService', () => {
|
|||||||
|
|
||||||
expect(activeModal?.component).toBe(ConfirmDeleteModalComponent);
|
expect(activeModal?.component).toBe(ConfirmDeleteModalComponent);
|
||||||
expect(activeModal?.config).toEqual({
|
expect(activeModal?.config).toEqual({
|
||||||
data: {
|
|
||||||
title: 'Eliminar producto',
|
title: 'Eliminar producto',
|
||||||
description: 'Se eliminara el producto.',
|
data: {
|
||||||
|
content: 'Se eliminara el producto.',
|
||||||
confirmLabel: 'Eliminar',
|
confirmLabel: 'Eliminar',
|
||||||
cancelLabel: 'Conservar',
|
cancelLabel: 'Conservar',
|
||||||
},
|
},
|
||||||
@@ -218,16 +202,16 @@ describe('ModalService', () => {
|
|||||||
it('opens the simple modal with default button label', () => {
|
it('opens the simple modal with default button label', () => {
|
||||||
service.openSimple({
|
service.openSimple({
|
||||||
title: 'Aviso',
|
title: 'Aviso',
|
||||||
description: 'Este es un aviso simple.',
|
content: 'Este es un aviso simple.',
|
||||||
});
|
});
|
||||||
|
|
||||||
const activeModal = service.activeModal();
|
const activeModal = service.activeModal();
|
||||||
|
|
||||||
expect(activeModal?.component).toBe(SimpleModalComponent);
|
expect(activeModal?.component).toBe(SimpleModalComponent);
|
||||||
expect(activeModal?.config).toEqual({
|
expect(activeModal?.config).toEqual({
|
||||||
data: {
|
|
||||||
title: 'Aviso',
|
title: 'Aviso',
|
||||||
description: 'Este es un aviso simple.',
|
data: {
|
||||||
|
content: 'Este es un aviso simple.',
|
||||||
buttonLabel: 'Entendido',
|
buttonLabel: 'Entendido',
|
||||||
},
|
},
|
||||||
size: 'md',
|
size: 'md',
|
||||||
@@ -240,7 +224,7 @@ describe('ModalService', () => {
|
|||||||
it('maps the simple modal close result to undefined', async () => {
|
it('maps the simple modal close result to undefined', async () => {
|
||||||
const result$ = service.openSimple({
|
const result$ = service.openSimple({
|
||||||
title: 'Aviso',
|
title: 'Aviso',
|
||||||
description: 'Este es un aviso simple.',
|
content: 'Este es un aviso simple.',
|
||||||
});
|
});
|
||||||
const activeModal = service.activeModal();
|
const activeModal = service.activeModal();
|
||||||
const resultPromise = firstValueFrom(result$);
|
const resultPromise = firstValueFrom(result$);
|
||||||
@@ -274,36 +258,6 @@ describe('ModalService', () => {
|
|||||||
showCloseButton: true,
|
showCloseButton: true,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('opens the image viewer fullscreen with normalized zoom limits', () => {
|
|
||||||
service.openImage({
|
|
||||||
title: 'Producto',
|
|
||||||
src: '/images/producto.webp',
|
|
||||||
alt: 'Producto visto de frente',
|
|
||||||
initialZoom: 8,
|
|
||||||
minZoom: 0,
|
|
||||||
maxZoom: 3,
|
|
||||||
});
|
|
||||||
|
|
||||||
const activeModal = service.activeModal();
|
|
||||||
|
|
||||||
expect(activeModal?.component).toBe(ImageModalComponent);
|
|
||||||
expect(activeModal?.config).toEqual({
|
|
||||||
title: 'Producto',
|
|
||||||
size: 'full',
|
|
||||||
presentation: 'fullscreen-media',
|
|
||||||
data: {
|
|
||||||
src: '/images/producto.webp',
|
|
||||||
alt: 'Producto visto de frente',
|
|
||||||
initialZoom: 3,
|
|
||||||
minZoom: 0.1,
|
|
||||||
maxZoom: 3,
|
|
||||||
},
|
|
||||||
closeOnBackdrop: true,
|
|
||||||
closeOnEscape: true,
|
|
||||||
showCloseButton: true,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
|
|||||||
@@ -2,19 +2,16 @@ import { InjectionToken, Injectable, Type, signal } from '@angular/core';
|
|||||||
import { Observable, Subject, map } from 'rxjs';
|
import { Observable, Subject, map } from 'rxjs';
|
||||||
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
||||||
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
||||||
import { ImageModalComponent } from '../../shared/components/image-modal/image-modal.component';
|
|
||||||
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
||||||
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
||||||
|
|
||||||
export type ModalSize = 'qr' | 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
export type ModalSize = 'qr' | 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
||||||
export type ModalDismissReason = 'backdrop' | 'escape' | 'programmatic' | 'replaced' | 'swipe';
|
export type ModalDismissReason = 'backdrop' | 'escape' | 'programmatic' | 'replaced';
|
||||||
export type ModalPresentation = 'dialog' | 'fullscreen-media';
|
|
||||||
|
|
||||||
export interface ModalConfig<TData = unknown> {
|
export interface ModalConfig<TData = unknown> {
|
||||||
title?: string;
|
title?: string;
|
||||||
data?: TData;
|
data?: TData;
|
||||||
size?: ModalSize;
|
size?: ModalSize;
|
||||||
presentation?: ModalPresentation;
|
|
||||||
closeOnBackdrop?: boolean;
|
closeOnBackdrop?: boolean;
|
||||||
closeOnEscape?: boolean;
|
closeOnEscape?: boolean;
|
||||||
showCloseButton?: boolean;
|
showCloseButton?: boolean;
|
||||||
@@ -31,28 +28,24 @@ export interface NormalizedModalConfig<TData = unknown> extends Omit<
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface ConfirmModalData {
|
export interface ConfirmModalData {
|
||||||
title: string;
|
content: string;
|
||||||
description?: string;
|
|
||||||
confirmLabel: string;
|
confirmLabel: string;
|
||||||
cancelLabel: string;
|
cancelLabel: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ConfirmModalConfig extends Omit<ModalConfig<ConfirmModalData>, 'data'> {
|
export interface ConfirmModalConfig extends Omit<ModalConfig<ConfirmModalData>, 'data'> {
|
||||||
title: string;
|
content: string;
|
||||||
description?: string;
|
|
||||||
confirmLabel?: string;
|
confirmLabel?: string;
|
||||||
cancelLabel?: string;
|
cancelLabel?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SimpleModalData {
|
export interface SimpleModalData {
|
||||||
title: string;
|
content: string;
|
||||||
description?: string;
|
|
||||||
buttonLabel: string;
|
buttonLabel: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SimpleModalConfig extends Omit<ModalConfig<SimpleModalData>, 'data'> {
|
export interface SimpleModalConfig extends Omit<ModalConfig<SimpleModalData>, 'data'> {
|
||||||
title: string;
|
content: string;
|
||||||
description?: string;
|
|
||||||
buttonLabel?: string;
|
buttonLabel?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,25 +62,6 @@ export interface QrModalConfig extends Omit<ModalConfig<QrModalData>, 'data' | '
|
|||||||
ticket: string;
|
ticket: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ImageModalData {
|
|
||||||
src: string;
|
|
||||||
alt: string;
|
|
||||||
initialZoom: number;
|
|
||||||
minZoom: number;
|
|
||||||
maxZoom: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ImageModalConfig extends Omit<
|
|
||||||
ModalConfig<ImageModalData>,
|
|
||||||
'data' | 'presentation' | 'size'
|
|
||||||
> {
|
|
||||||
src: string;
|
|
||||||
alt: string;
|
|
||||||
initialZoom?: number;
|
|
||||||
minZoom?: number;
|
|
||||||
maxZoom?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ActiveModalState<TResult = unknown, TData = unknown> {
|
export interface ActiveModalState<TResult = unknown, TData = unknown> {
|
||||||
component: Type<unknown>;
|
component: Type<unknown>;
|
||||||
config: NormalizedModalConfig<TData>;
|
config: NormalizedModalConfig<TData>;
|
||||||
@@ -221,40 +195,13 @@ export class ModalService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
openImage(config: ImageModalConfig): Observable<void> {
|
|
||||||
return this.openImageRef(config).afterClosed$.pipe(map(() => undefined));
|
|
||||||
}
|
|
||||||
|
|
||||||
openImageRef(config: ImageModalConfig): ModalRef<void> {
|
|
||||||
const { src, alt, initialZoom = 1, minZoom = 1, maxZoom = 4, ...modalConfig } = config;
|
|
||||||
const normalizedMinZoom = Math.max(0.1, minZoom);
|
|
||||||
const normalizedMaxZoom = Math.max(normalizedMinZoom, maxZoom);
|
|
||||||
const normalizedInitialZoom = Math.min(
|
|
||||||
normalizedMaxZoom,
|
|
||||||
Math.max(normalizedMinZoom, initialZoom),
|
|
||||||
);
|
|
||||||
|
|
||||||
return this.open(ImageModalComponent, {
|
|
||||||
...modalConfig,
|
|
||||||
size: 'full',
|
|
||||||
presentation: 'fullscreen-media',
|
|
||||||
data: {
|
|
||||||
src,
|
|
||||||
alt,
|
|
||||||
initialZoom: normalizedInitialZoom,
|
|
||||||
minZoom: normalizedMinZoom,
|
|
||||||
maxZoom: normalizedMaxZoom,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private close<TResult>(ref: ModalRef<TResult>, result?: TResult): void {
|
private close<TResult>(ref: ModalRef<TResult>, result?: TResult): void {
|
||||||
if (this.activeModalState()?.ref !== ref) {
|
if (this.activeModalState()?.ref !== ref) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.activeModalState.set(null);
|
|
||||||
ref.finalize(result);
|
ref.finalize(result);
|
||||||
|
this.activeModalState.set(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
private dismiss<TResult>(
|
private dismiss<TResult>(
|
||||||
@@ -265,8 +212,8 @@ export class ModalService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.activeModalState.set(null);
|
|
||||||
ref.finalize(undefined, reason);
|
ref.finalize(undefined, reason);
|
||||||
|
this.activeModalState.set(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeConfig<TData>(config: ModalConfig<TData>): NormalizedModalConfig<TData> {
|
private normalizeConfig<TData>(config: ModalConfig<TData>): NormalizedModalConfig<TData> {
|
||||||
@@ -278,8 +225,7 @@ export class ModalService {
|
|||||||
|
|
||||||
private buildConfirmModalConfig(config: ConfirmModalConfig): ModalConfig<ConfirmModalData> {
|
private buildConfirmModalConfig(config: ConfirmModalConfig): ModalConfig<ConfirmModalData> {
|
||||||
const {
|
const {
|
||||||
title,
|
content,
|
||||||
description,
|
|
||||||
confirmLabel = DEFAULT_CONFIRM_MODAL_LABELS.confirmLabel,
|
confirmLabel = DEFAULT_CONFIRM_MODAL_LABELS.confirmLabel,
|
||||||
cancelLabel = DEFAULT_CONFIRM_MODAL_LABELS.cancelLabel,
|
cancelLabel = DEFAULT_CONFIRM_MODAL_LABELS.cancelLabel,
|
||||||
...modalConfig
|
...modalConfig
|
||||||
@@ -288,8 +234,7 @@ export class ModalService {
|
|||||||
return {
|
return {
|
||||||
...modalConfig,
|
...modalConfig,
|
||||||
data: {
|
data: {
|
||||||
title,
|
content,
|
||||||
description,
|
|
||||||
confirmLabel,
|
confirmLabel,
|
||||||
cancelLabel,
|
cancelLabel,
|
||||||
},
|
},
|
||||||
@@ -297,13 +242,12 @@ export class ModalService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private buildSimpleModalConfig(config: SimpleModalConfig): ModalConfig<SimpleModalData> {
|
private buildSimpleModalConfig(config: SimpleModalConfig): ModalConfig<SimpleModalData> {
|
||||||
const { title, description, buttonLabel = 'Entendido', ...modalConfig } = config;
|
const { content, buttonLabel = 'Entendido', ...modalConfig } = config;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...modalConfig,
|
...modalConfig,
|
||||||
data: {
|
data: {
|
||||||
title,
|
content,
|
||||||
description,
|
|
||||||
buttonLabel,
|
buttonLabel,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -19,6 +19,16 @@ export interface BankAccount {
|
|||||||
cvu: string;
|
cvu: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface WebsiteType {
|
||||||
|
codigo: string;
|
||||||
|
nombre: string;
|
||||||
|
primary_color: string | null;
|
||||||
|
secondary_color: string | null;
|
||||||
|
danger_color: string | null;
|
||||||
|
success_color: string | null;
|
||||||
|
site_logo: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface HeroConfig {
|
export interface HeroConfig {
|
||||||
background_image_id?: string | ResponsiveImage | null;
|
background_image_id?: string | ResponsiveImage | null;
|
||||||
title_html?: string | null;
|
title_html?: string | null;
|
||||||
@@ -41,8 +51,6 @@ export interface EventDate {
|
|||||||
date: string;
|
date: string;
|
||||||
start_time: string;
|
start_time: string;
|
||||||
end_time: string;
|
end_time: string;
|
||||||
info_text: string | null;
|
|
||||||
isCanceled: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface EventConfig {
|
export interface EventConfig {
|
||||||
@@ -59,29 +67,16 @@ export interface ActiveEventDate {
|
|||||||
date: string;
|
date: string;
|
||||||
time_start: string;
|
time_start: string;
|
||||||
time_end: string;
|
time_end: string;
|
||||||
info_text: string | null;
|
|
||||||
isCanceled: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TenantEvent {
|
export interface TenantEvent {
|
||||||
id: number;
|
|
||||||
title: string;
|
title: string;
|
||||||
subtitle: string | null;
|
location: string;
|
||||||
description: string | null;
|
|
||||||
location: string | null;
|
|
||||||
date_text: string | null;
|
|
||||||
dates: ActiveEventDate[];
|
dates: ActiveEventDate[];
|
||||||
social_media: SocialMedia[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WebsiteExtras {
|
export interface WebsiteExtras {
|
||||||
carousel?: string[];
|
carousel?: string[];
|
||||||
immersiveHeroCarousel?: string[];
|
|
||||||
immersiveHero?: {
|
|
||||||
eyebrow: string;
|
|
||||||
title: string;
|
|
||||||
description: string;
|
|
||||||
};
|
|
||||||
heroConfig?: HeroConfig | null;
|
heroConfig?: HeroConfig | null;
|
||||||
additionalInfoConfig?: AdditionalInfoConfig | null;
|
additionalInfoConfig?: AdditionalInfoConfig | null;
|
||||||
[extraName: string]: unknown;
|
[extraName: string]: unknown;
|
||||||
@@ -118,7 +113,6 @@ export interface Tenant {
|
|||||||
dominio: string;
|
dominio: string;
|
||||||
base_path?: string;
|
base_path?: string;
|
||||||
site_title?: string | null;
|
site_title?: string | null;
|
||||||
asset_url?: string | null;
|
|
||||||
address?: string | null;
|
address?: string | null;
|
||||||
phone?: string | null;
|
phone?: string | null;
|
||||||
favicon?: string | null;
|
favicon?: string | null;
|
||||||
@@ -132,8 +126,9 @@ export interface Tenant {
|
|||||||
footer_logo: string;
|
footer_logo: string;
|
||||||
header_bg_image?: string | null;
|
header_bg_image?: string | null;
|
||||||
footer_bg_image?: string | null;
|
footer_bg_image?: string | null;
|
||||||
storefront_website_type_code?: string | null;
|
website_type_code?: string | null;
|
||||||
header_type?: 'standard' | 'immersive';
|
website_type?: WebsiteType | null;
|
||||||
|
event_date_text?: string | null;
|
||||||
extras?: WebsiteExtras;
|
extras?: WebsiteExtras;
|
||||||
event?: TenantEvent | null;
|
event?: TenantEvent | null;
|
||||||
selected_bank_account_id?: number | null;
|
selected_bank_account_id?: number | null;
|
||||||
@@ -147,10 +142,6 @@ export interface Tenant {
|
|||||||
cart_editing_policy?: CartEditingPolicy;
|
cart_editing_policy?: CartEditingPolicy;
|
||||||
checkout_editing_policy?: CartEditingPolicy;
|
checkout_editing_policy?: CartEditingPolicy;
|
||||||
display_cart_item_images?: boolean;
|
display_cart_item_images?: boolean;
|
||||||
allow_ticket_refund?: boolean;
|
|
||||||
allow_ticket_total_refund?: boolean;
|
|
||||||
allow_ticket_partial_refund?: boolean;
|
|
||||||
ticket_partial_refund_percentage?: string;
|
|
||||||
social_media?: SocialMedia[];
|
social_media?: SocialMedia[];
|
||||||
menues?: Menu[];
|
menues?: Menu[];
|
||||||
categories: Category[];
|
categories: Category[];
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ const tenant: Tenant = {
|
|||||||
codigo: 'test',
|
codigo: 'test',
|
||||||
nombre: 'Test Tenant',
|
nombre: 'Test Tenant',
|
||||||
dominio: 'localhost',
|
dominio: 'localhost',
|
||||||
asset_url: 'https://s3.example.com/assets',
|
|
||||||
primary_color: '#6376F3',
|
primary_color: '#6376F3',
|
||||||
secondary_color: '#A0A0A0',
|
secondary_color: '#A0A0A0',
|
||||||
danger_color: '#FF8888',
|
danger_color: '#FF8888',
|
||||||
@@ -45,7 +44,6 @@ const tenantResponse: TenantBootstrapResponse = {
|
|||||||
|
|
||||||
describe('TenantService', () => {
|
describe('TenantService', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
document.head.querySelectorAll('link[rel="preconnect"]').forEach((link) => link.remove());
|
|
||||||
try {
|
try {
|
||||||
window.history.replaceState({}, '', 'http://localhost:4200/');
|
window.history.replaceState({}, '', 'http://localhost:4200/');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -74,9 +72,6 @@ describe('TenantService', () => {
|
|||||||
expect(service.status()).toBe('ready');
|
expect(service.status()).toBe('ready');
|
||||||
expect(service.tenant()).toEqual(tenant);
|
expect(service.tenant()).toEqual(tenant);
|
||||||
expect(service.getTenant()).toEqual(tenant);
|
expect(service.getTenant()).toEqual(tenant);
|
||||||
expect(
|
|
||||||
document.head.querySelector('link[rel="preconnect"][href="https://s3.example.com/"]'),
|
|
||||||
).not.toBeNull();
|
|
||||||
|
|
||||||
httpController.verify();
|
httpController.verify();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { DOCUMENT, isPlatformBrowser, isPlatformServer } from '@angular/common';
|
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import {
|
import {
|
||||||
inject,
|
inject,
|
||||||
@@ -26,7 +26,6 @@ import {
|
|||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class TenantService extends BaseApiService {
|
export class TenantService extends BaseApiService {
|
||||||
private readonly document = inject(DOCUMENT);
|
|
||||||
private readonly platformId = inject(PLATFORM_ID);
|
private readonly platformId = inject(PLATFORM_ID);
|
||||||
private readonly request = inject(REQUEST, { optional: true });
|
private readonly request = inject(REQUEST, { optional: true });
|
||||||
private readonly responseInit = inject(RESPONSE_INIT, { optional: true });
|
private readonly responseInit = inject(RESPONSE_INIT, { optional: true });
|
||||||
@@ -183,44 +182,10 @@ export class TenantService extends BaseApiService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private setReady(tenant: Tenant): void {
|
private setReady(tenant: Tenant): void {
|
||||||
if (isPlatformBrowser(this.platformId) && !environment.production) {
|
|
||||||
console.info('[Tenant bootstrap]', tenant);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.ensureAssetPreconnect(tenant.asset_url);
|
|
||||||
this.tenantState.set(tenant);
|
this.tenantState.set(tenant);
|
||||||
this.statusState.set('ready');
|
this.statusState.set('ready');
|
||||||
}
|
}
|
||||||
|
|
||||||
private ensureAssetPreconnect(assetUrl: string | null | undefined): void {
|
|
||||||
if (!assetUrl) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let origin: string;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const url = new URL(assetUrl);
|
|
||||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
origin = url.origin;
|
|
||||||
} catch {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const existingPreconnects =
|
|
||||||
this.document.head.querySelectorAll<HTMLLinkElement>('link[rel="preconnect"]');
|
|
||||||
if ([...existingPreconnects].some((link) => link.href === `${origin}/`)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const link = this.document.createElement('link');
|
|
||||||
link.rel = 'preconnect';
|
|
||||||
link.href = origin;
|
|
||||||
this.document.head.append(link);
|
|
||||||
}
|
|
||||||
|
|
||||||
private setNotFound(): void {
|
private setNotFound(): void {
|
||||||
this.tenantState.set(null);
|
this.tenantState.set(null);
|
||||||
this.statusState.set('not-found');
|
this.statusState.set('not-found');
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { DOCUMENT } from '@angular/common';
|
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { vi } from 'vitest';
|
import { vi } from 'vitest';
|
||||||
import { ToastService } from './toast.service';
|
import { ToastService } from './toast.service';
|
||||||
@@ -7,16 +6,14 @@ describe('ToastService', () => {
|
|||||||
let service: ToastService;
|
let service: ToastService;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.useFakeTimers();
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [ToastService]
|
providers: [ToastService]
|
||||||
});
|
});
|
||||||
TestBed.inject(DOCUMENT).defaultView?.sessionStorage.removeItem('shopit.pending-toast');
|
|
||||||
service = TestBed.inject(ToastService);
|
service = TestBed.inject(ToastService);
|
||||||
|
vi.useFakeTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
TestBed.inject(DOCUMENT).defaultView?.sessionStorage.removeItem('shopit.pending-toast');
|
|
||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -101,23 +98,4 @@ describe('ToastService', () => {
|
|||||||
|
|
||||||
expect(service.toasts().length).toBe(1);
|
expect(service.toasts().length).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should restore a toast queued for after a full page reload', () => {
|
|
||||||
service.showAfterReload('Sesión iniciada correctamente.', 'success', 0);
|
|
||||||
|
|
||||||
TestBed.resetTestingModule();
|
|
||||||
TestBed.configureTestingModule({ providers: [ToastService] });
|
|
||||||
service = TestBed.inject(ToastService);
|
|
||||||
|
|
||||||
expect(service.toasts()).toEqual([
|
|
||||||
expect.objectContaining({
|
|
||||||
message: 'Sesión iniciada correctamente.',
|
|
||||||
type: 'success',
|
|
||||||
duration: 0,
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
expect(
|
|
||||||
TestBed.inject(DOCUMENT).defaultView?.sessionStorage.getItem('shopit.pending-toast'),
|
|
||||||
).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
|
import { Injectable, signal } from '@angular/core';
|
||||||
import { inject, Injectable, PLATFORM_ID, signal } from '@angular/core';
|
|
||||||
|
|
||||||
const PENDING_TOAST_STORAGE_KEY = 'shopit.pending-toast';
|
|
||||||
|
|
||||||
export interface Toast {
|
export interface Toast {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -14,15 +11,9 @@ export interface Toast {
|
|||||||
providedIn: 'root'
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class ToastService {
|
export class ToastService {
|
||||||
private readonly document = inject(DOCUMENT);
|
|
||||||
private readonly platformId = inject(PLATFORM_ID);
|
|
||||||
private readonly toastsSignal = signal<Toast[]>([]);
|
private readonly toastsSignal = signal<Toast[]>([]);
|
||||||
readonly toasts = this.toastsSignal.asReadonly();
|
readonly toasts = this.toastsSignal.asReadonly();
|
||||||
|
|
||||||
constructor() {
|
|
||||||
this.restorePendingToast();
|
|
||||||
}
|
|
||||||
|
|
||||||
show(message: string, type: 'success' | 'danger' | 'info' = 'info', duration = 3000): string {
|
show(message: string, type: 'success' | 'danger' | 'info' = 'info', duration = 3000): string {
|
||||||
const id = Math.random().toString(36).substring(2, 9);
|
const id = Math.random().toString(36).substring(2, 9);
|
||||||
const newToast: Toast = { id, message, type, duration };
|
const newToast: Toast = { id, message, type, duration };
|
||||||
@@ -50,50 +41,7 @@ export class ToastService {
|
|||||||
return this.show(message, 'success', duration);
|
return this.show(message, 'success', duration);
|
||||||
}
|
}
|
||||||
|
|
||||||
showAfterReload(
|
|
||||||
message: string,
|
|
||||||
type: Toast['type'] = 'info',
|
|
||||||
duration = 3000,
|
|
||||||
): void {
|
|
||||||
if (!isPlatformBrowser(this.platformId)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.document.defaultView?.sessionStorage.setItem(
|
|
||||||
PENDING_TOAST_STORAGE_KEY,
|
|
||||||
JSON.stringify({ message, type, duration }),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
dismiss(id: string): void {
|
dismiss(id: string): void {
|
||||||
this.toastsSignal.update((toasts) => toasts.filter((t) => t.id !== id));
|
this.toastsSignal.update((toasts) => toasts.filter((t) => t.id !== id));
|
||||||
}
|
}
|
||||||
|
|
||||||
private restorePendingToast(): void {
|
|
||||||
if (!isPlatformBrowser(this.platformId)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const storage = this.document.defaultView?.sessionStorage;
|
|
||||||
const pendingToast = storage?.getItem(PENDING_TOAST_STORAGE_KEY);
|
|
||||||
|
|
||||||
if (!pendingToast) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
storage?.removeItem(PENDING_TOAST_STORAGE_KEY);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(pendingToast) as Partial<Toast>;
|
|
||||||
|
|
||||||
if (
|
|
||||||
typeof parsed.message === 'string' &&
|
|
||||||
(parsed.type === 'success' || parsed.type === 'danger' || parsed.type === 'info')
|
|
||||||
) {
|
|
||||||
this.show(parsed.message, parsed.type, parsed.duration);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Ignore malformed session data left by an older or interrupted client.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,9 +83,6 @@
|
|||||||
Abrir modal ancho
|
Abrir modal ancho
|
||||||
</app-button>
|
</app-button>
|
||||||
<app-button (click)="openSimpleModal()"> Abrir simple modal </app-button>
|
<app-button (click)="openSimpleModal()"> Abrir simple modal </app-button>
|
||||||
<app-button variant="secondary" (click)="openImageModal()">
|
|
||||||
Abrir visor de imagen
|
|
||||||
</app-button>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-showcase__result" data-testid="modal-last-result">
|
<div class="modal-showcase__result" data-testid="modal-last-result">
|
||||||
{{ lastModalResult }}
|
{{ lastModalResult }}
|
||||||
|
|||||||
@@ -51,7 +51,6 @@ function createModalServiceStub() {
|
|||||||
open: vi.fn(),
|
open: vi.fn(),
|
||||||
openConfirm: vi.fn().mockReturnValue(of(true)),
|
openConfirm: vi.fn().mockReturnValue(of(true)),
|
||||||
openConfirmDelete: vi.fn().mockReturnValue(of(false)),
|
openConfirmDelete: vi.fn().mockReturnValue(of(false)),
|
||||||
openImage: vi.fn().mockReturnValue(of(undefined)),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,9 +281,6 @@ describe('ReutilizablesTestPageComponent', () => {
|
|||||||
const deleteButton = buttons.find((button) =>
|
const deleteButton = buttons.find((button) =>
|
||||||
button.textContent?.includes('Abrir confirm delete'),
|
button.textContent?.includes('Abrir confirm delete'),
|
||||||
) as HTMLButtonElement;
|
) as HTMLButtonElement;
|
||||||
const imageButton = buttons.find((button) =>
|
|
||||||
button.textContent?.includes('Abrir visor de imagen'),
|
|
||||||
) as HTMLButtonElement;
|
|
||||||
|
|
||||||
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
||||||
'Todavia no se abrio ningun modal.',
|
'Todavia no se abrio ningun modal.',
|
||||||
@@ -294,25 +290,18 @@ describe('ReutilizablesTestPageComponent', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
deleteButton.click();
|
deleteButton.click();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
imageButton.click();
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(modalServiceStub.openConfirm).toHaveBeenCalledWith({
|
expect(modalServiceStub.openConfirm).toHaveBeenCalledWith({
|
||||||
title: 'Confirmar accion',
|
title: 'Confirmar accion',
|
||||||
description: 'Caso base para verificar apertura, cierre y devolucion de resultado.',
|
content: 'Caso base para verificar apertura, cierre y devolucion de resultado.',
|
||||||
confirmLabel: 'Confirmar',
|
confirmLabel: 'Confirmar',
|
||||||
});
|
});
|
||||||
expect(modalServiceStub.openConfirmDelete).toHaveBeenCalledWith({
|
expect(modalServiceStub.openConfirmDelete).toHaveBeenCalledWith({
|
||||||
title: 'Eliminar producto',
|
title: 'Eliminar producto',
|
||||||
description:
|
content:
|
||||||
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
||||||
confirmLabel: 'Eliminar',
|
confirmLabel: 'Eliminar',
|
||||||
});
|
});
|
||||||
expect(modalServiceStub.openImage).toHaveBeenCalledWith({
|
|
||||||
title: 'Mochila urbana roja',
|
|
||||||
src: '/images/carousel-mochila-roja.webp',
|
|
||||||
alt: 'Mochila urbana roja vista de frente',
|
|
||||||
});
|
|
||||||
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
||||||
'Resultado: false',
|
'Resultado: false',
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { StoreSectionComponent } from '../../../../shared/components/store-secti
|
|||||||
import { ModalService } from '../../../../core/services/modal.service';
|
import { ModalService } from '../../../../core/services/modal.service';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
|
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||||
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
||||||
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
||||||
import { CarouselComponent } from '../../../../shared/components/carousel/carousel.component';
|
import { CarouselComponent } from '../../../../shared/components/carousel/carousel.component';
|
||||||
@@ -232,7 +233,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1001,
|
id: 1001,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(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 +244,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1002,
|
id: 1002,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(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 +255,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1003,
|
id: 1003,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(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 +266,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1004,
|
id: 1004,
|
||||||
precio: 200000,
|
precio: 200000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(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 +277,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1005,
|
id: 1005,
|
||||||
precio: 200000,
|
precio: 200000,
|
||||||
maximum_addable_quantity: 0,
|
availability: createCatalogAvailability(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 +288,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1006,
|
id: 1006,
|
||||||
precio: 100000,
|
precio: 100000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('b', 'Sector B'),
|
sector: ticketOption('b', 'Sector B'),
|
||||||
@@ -298,7 +299,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1007,
|
id: 1007,
|
||||||
precio: 100000,
|
precio: 100000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('b', 'Sector B'),
|
sector: ticketOption('b', 'Sector B'),
|
||||||
@@ -309,7 +310,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1008,
|
id: 1008,
|
||||||
precio: 90000,
|
precio: 90000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
@@ -320,7 +321,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1009,
|
id: 1009,
|
||||||
precio: 65000,
|
precio: 65000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
@@ -331,7 +332,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1010,
|
id: 1010,
|
||||||
precio: 40000,
|
precio: 40000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
@@ -448,7 +449,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
protected openBasicModal(): void {
|
protected openBasicModal(): void {
|
||||||
this.openConfirmModal({
|
this.openConfirmModal({
|
||||||
title: 'Confirmar accion',
|
title: 'Confirmar accion',
|
||||||
description: 'Caso base para verificar apertura, cierre y devolucion de resultado.',
|
content: 'Caso base para verificar apertura, cierre y devolucion de resultado.',
|
||||||
confirmLabel: 'Confirmar',
|
confirmLabel: 'Confirmar',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -456,7 +457,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
protected openConfirmDeleteModal(): void {
|
protected openConfirmDeleteModal(): void {
|
||||||
this.openConfirmDelete({
|
this.openConfirmDelete({
|
||||||
title: 'Eliminar producto',
|
title: 'Eliminar producto',
|
||||||
description:
|
content:
|
||||||
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
||||||
confirmLabel: 'Eliminar',
|
confirmLabel: 'Eliminar',
|
||||||
});
|
});
|
||||||
@@ -465,7 +466,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
protected openLockedModal(): void {
|
protected openLockedModal(): void {
|
||||||
this.openConfirmModal({
|
this.openConfirmModal({
|
||||||
title: 'Modal bloqueado',
|
title: 'Modal bloqueado',
|
||||||
description: 'Este modal no se cierra tocando el backdrop ni con la tecla Escape.',
|
content: 'Este modal no se cierra tocando el backdrop ni con la tecla Escape.',
|
||||||
confirmLabel: 'Entendido',
|
confirmLabel: 'Entendido',
|
||||||
closeOnBackdrop: false,
|
closeOnBackdrop: false,
|
||||||
closeOnEscape: false,
|
closeOnEscape: false,
|
||||||
@@ -475,7 +476,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
protected openWideModal(): void {
|
protected openWideModal(): void {
|
||||||
this.openConfirmModal({
|
this.openConfirmModal({
|
||||||
title: 'Modal ancho',
|
title: 'Modal ancho',
|
||||||
description: 'Demuestra una variante visual mas amplia para contenido mas pesado.',
|
content: 'Demuestra una variante visual mas amplia para contenido mas pesado.',
|
||||||
confirmLabel: 'Seguir',
|
confirmLabel: 'Seguir',
|
||||||
size: 'xl',
|
size: 'xl',
|
||||||
});
|
});
|
||||||
@@ -485,7 +486,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
this.modalService
|
this.modalService
|
||||||
.openSimple({
|
.openSimple({
|
||||||
title: 'Mensaje del sistema',
|
title: 'Mensaje del sistema',
|
||||||
description: 'Este es un mensaje simple del sistema que no requiere confirmación.',
|
content: 'Este es un mensaje simple del sistema que no requiere confirmación.',
|
||||||
buttonLabel: 'Entendido',
|
buttonLabel: 'Entendido',
|
||||||
})
|
})
|
||||||
.subscribe(() => {
|
.subscribe(() => {
|
||||||
@@ -493,14 +494,6 @@ export class ReutilizablesTestPageComponent {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected openImageModal(): void {
|
|
||||||
this.modalService.openImage({
|
|
||||||
title: 'Mochila urbana roja',
|
|
||||||
src: '/images/carousel-mochila-roja.webp',
|
|
||||||
alt: 'Mochila urbana roja vista de frente',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private openConfirmModal(config: Parameters<ModalService['openConfirm']>[0]): void {
|
private openConfirmModal(config: Parameters<ModalService['openConfirm']>[0]): void {
|
||||||
this.modalService.openConfirm(config).subscribe((confirmed) => {
|
this.modalService.openConfirm(config).subscribe((confirmed) => {
|
||||||
this.lastModalResult = `Resultado: ${confirmed}`;
|
this.lastModalResult = `Resultado: ${confirmed}`;
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
<a class="event-card" [routerLink]="['/evento', event().id]">
|
|
||||||
<div class="event-card__image">
|
|
||||||
@if (event().image) {
|
|
||||||
<img [src]="event().image" [alt]="event().title" />
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
<div class="event-card__body">
|
|
||||||
<h2 class="event-card__title">{{ event().title | uppercase }}</h2>
|
|
||||||
@if (event().subtitle) {
|
|
||||||
<p class="event-card__subtitle">{{ event().subtitle }}</p>
|
|
||||||
}
|
|
||||||
@if (event().date_text) {
|
|
||||||
<p class="event-card__meta"><i class="fa-regular fa-calendar" aria-hidden="true"></i>{{ event().date_text }}</p>
|
|
||||||
}
|
|
||||||
@if (event().location) {
|
|
||||||
<p class="event-card__meta"><i class="fa-solid fa-location-dot" aria-hidden="true"></i>{{ event().location }}</p>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</a>
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
:host { display: block; min-width: 0; }
|
|
||||||
.event-card { display: block; height: 100%; color: inherit; background: #fff; text-decoration: none; box-shadow: 0 12px 30px rgba(0, 0, 0, .05); transition: transform .2s, box-shadow .2s; }
|
|
||||||
.event-card:hover { transform: translateY(-3px); box-shadow: 0 16px 32px rgba(0, 0, 0, .1); }
|
|
||||||
.event-card:focus-visible { outline: 2px solid var(--tenant-primary); outline-offset: 3px; }
|
|
||||||
.event-card__image { width: 100%; aspect-ratio: 1.43; background: #e5e6e7; }
|
|
||||||
.event-card__image img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
|
||||||
.event-card__body { padding: 1rem 1.1rem 1.2rem; }
|
|
||||||
.event-card__title { margin: 0; font-size: 15px; font-weight: 700; line-height: 1.3; color: #666666; }
|
|
||||||
.event-card__subtitle { margin: .25rem 0 .8rem; font-size: 12px; font-weight: 400; color: #666666; }
|
|
||||||
.event-card__meta { display: flex; align-items: baseline; gap: .45rem; margin: .2rem 0 0; font-size: 9px; font-weight: 400; font-style: italic; color: #666666; }
|
|
||||||
.event-card__meta i { width: .75rem; flex: none; }
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
|
|
||||||
import { UpperCasePipe } from '@angular/common';
|
|
||||||
import { RouterLink } from '@angular/router';
|
|
||||||
|
|
||||||
import { StoreEvent } from '../../../../core/services/event/event.interface';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'app-event-card',
|
|
||||||
imports: [RouterLink, UpperCasePipe],
|
|
||||||
templateUrl: './event-card.component.html',
|
|
||||||
styleUrl: './event-card.component.scss',
|
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
||||||
})
|
|
||||||
export class EventCardComponent {
|
|
||||||
readonly event = input.required<StoreEvent>();
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
@if (loading()) {
|
|
||||||
<p class="event-list__message">Cargando eventos...</p>
|
|
||||||
} @else if (error()) {
|
|
||||||
<p class="event-list__message" role="alert">No pudimos cargar los eventos.</p>
|
|
||||||
} @else if (results(); as page) {
|
|
||||||
@if (page.data.length) {
|
|
||||||
<div class="event-list__grid">
|
|
||||||
@for (event of page.data; track event.id) {
|
|
||||||
<app-event-card [event]="event" />
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
@if (page.meta.last_page > 1) {
|
|
||||||
<div class="event-list__pagination">
|
|
||||||
<app-paginator [page]="page.meta.current_page" [totalPages]="page.meta.last_page" (pageChange)="changePage($event)" />
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
} @else {
|
|
||||||
<p class="event-list__message">{{ search() ? 'No encontramos eventos para tu búsqueda.' : 'No hay eventos disponibles en este momento.' }}</p>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
.event-list__grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: clamp(1.25rem, 3vw, 2.5rem); }
|
|
||||||
.event-list__pagination { display: flex; justify-content: center; margin-top: 3rem; }
|
|
||||||
.event-list__message { text-align: center; padding: 2rem 0; }
|
|
||||||
@media (max-width: 767.98px) { .event-list__grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
|
||||||
@media (max-width: 479.98px) { .event-list__grid { grid-template-columns: 1fr; } }
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
import { ChangeDetectionStrategy, Component, DestroyRef, inject, input, OnInit, signal } from '@angular/core';
|
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
|
||||||
import { catchError, distinctUntilChanged, map, of, switchMap, tap } from 'rxjs';
|
|
||||||
|
|
||||||
import { EventService } from '../../../../core/services/event/event.service';
|
|
||||||
import { StoreEventPage } from '../../../../core/services/event/event.interface';
|
|
||||||
import { PaginatorComponent } from '../../../../shared/components/paginator/paginator.component';
|
|
||||||
import { EventCardComponent } from '../event-card/event-card.component';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'app-event-list',
|
|
||||||
imports: [EventCardComponent, PaginatorComponent],
|
|
||||||
templateUrl: './event-list.component.html',
|
|
||||||
styleUrl: './event-list.component.scss',
|
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
||||||
})
|
|
||||||
export class EventListComponent implements OnInit {
|
|
||||||
private readonly eventService = inject(EventService);
|
|
||||||
private readonly route = inject(ActivatedRoute);
|
|
||||||
private readonly router = inject(Router);
|
|
||||||
private readonly destroyRef = inject(DestroyRef);
|
|
||||||
|
|
||||||
readonly search = input(false);
|
|
||||||
protected readonly results = signal<StoreEventPage | null>(null);
|
|
||||||
protected readonly loading = signal(true);
|
|
||||||
protected readonly error = signal(false);
|
|
||||||
protected readonly query = signal('');
|
|
||||||
|
|
||||||
ngOnInit(): void {
|
|
||||||
this.route.queryParamMap.pipe(
|
|
||||||
map((params) => {
|
|
||||||
const requestedPage = Number(params.get('page'));
|
|
||||||
return {
|
|
||||||
page: Number.isSafeInteger(requestedPage) && requestedPage > 0 ? requestedPage : 1,
|
|
||||||
query: this.search() ? (params.get('q') ?? '').trim() : '',
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
distinctUntilChanged((a, b) => a.page === b.page && a.query === b.query),
|
|
||||||
tap(({ query }) => {
|
|
||||||
this.query.set(query);
|
|
||||||
this.loading.set(true);
|
|
||||||
this.error.set(false);
|
|
||||||
this.results.set(null);
|
|
||||||
}),
|
|
||||||
switchMap(({ page, query }) => this.eventService.list(page, query).pipe(
|
|
||||||
catchError(() => {
|
|
||||||
this.error.set(true);
|
|
||||||
return of(null);
|
|
||||||
}),
|
|
||||||
)),
|
|
||||||
takeUntilDestroyed(this.destroyRef),
|
|
||||||
).subscribe((results) => {
|
|
||||||
this.results.set(results);
|
|
||||||
this.loading.set(false);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
protected changePage(page: number): void {
|
|
||||||
void this.router.navigate([], {
|
|
||||||
relativeTo: this.route,
|
|
||||||
queryParams: { page: page === 1 ? null : page },
|
|
||||||
queryParamsHandling: 'merge',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
[attr.aria-label]="option.label"
|
[attr.aria-label]="option.label"
|
||||||
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
||||||
[title]="option.label"
|
[title]="option.label"
|
||||||
[disabled]="!availableOptions()[attribute.codigo][option.id]"
|
[disabled]="disabled() || !availableOptions()[attribute.codigo][option.id]"
|
||||||
(click)="selectAttributeOption(attribute, option)"
|
(click)="selectAttributeOption(attribute, option)"
|
||||||
>
|
>
|
||||||
<span class="visually-hidden">{{ option.label }}</span>
|
<span class="visually-hidden">{{ option.label }}</span>
|
||||||
@@ -33,7 +33,7 @@
|
|||||||
!availableOptions()[attribute.codigo][option.id]
|
!availableOptions()[attribute.codigo][option.id]
|
||||||
"
|
"
|
||||||
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
||||||
[disabled]="!availableOptions()[attribute.codigo][option.id]"
|
[disabled]="disabled() || !availableOptions()[attribute.codigo][option.id]"
|
||||||
(click)="selectAttributeOption(attribute, option)"
|
(click)="selectAttributeOption(attribute, option)"
|
||||||
>
|
>
|
||||||
{{ option.label }}
|
{{ option.label }}
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { beforeEach, describe, expect, it } from 'vitest';
|
import { beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
import {
|
import { ProductAttribute } from '../../../../core/services/catalog/catalog.interface';
|
||||||
CatalogItemVariant,
|
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||||
ProductAttribute,
|
|
||||||
} from '../../../../core/services/catalog/catalog.interface';
|
|
||||||
import { ProductAttributeSelectorComponent } from './product-attribute-selector.component';
|
import { ProductAttributeSelectorComponent } from './product-attribute-selector.component';
|
||||||
|
|
||||||
describe('ProductAttributeSelectorComponent', () => {
|
describe('ProductAttributeSelectorComponent', () => {
|
||||||
@@ -27,63 +25,6 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
});
|
});
|
||||||
|
|
||||||
it.each([{ size: { value: 'S', label: 'Small' } }, { size: [{ value: 'S', label: 'Small' }] }])(
|
|
||||||
'initializes and matches structured variant values: %j',
|
|
||||||
(values) => {
|
|
||||||
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
|
||||||
const variant: CatalogItemVariant = { id: 1, maximum_addable_quantity: null, values };
|
|
||||||
const emittedIds: Array<number | null> = [];
|
|
||||||
fixture.componentInstance.variantChange.subscribe((selected) =>
|
|
||||||
emittedIds.push(selected?.id ?? null),
|
|
||||||
);
|
|
||||||
fixture.componentRef.setInput('attributes', [sizeAttribute]);
|
|
||||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
|
||||||
fixture.componentRef.setInput('variants', [variant]);
|
|
||||||
fixture.componentRef.setInput('selectedVariant', variant);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
const button = fixture.nativeElement.querySelector(
|
|
||||||
'.attribute-selector__text-option',
|
|
||||||
) as HTMLButtonElement;
|
|
||||||
expect(button.getAttribute('aria-pressed')).toBe('true');
|
|
||||||
expect(button.disabled).toBe(false);
|
|
||||||
expect(emittedIds.at(-1)).toBe(1);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
it.each([0, 2, null])(
|
|
||||||
'uses maximum quantity %s for alternatives to a preselected option',
|
|
||||||
(maximum) => {
|
|
||||||
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
|
||||||
const variants: CatalogItemVariant[] = [
|
|
||||||
{ id: 1, maximum_addable_quantity: 3, values: { size: { value: 'S', label: 'Small' } } },
|
|
||||||
{
|
|
||||||
id: 2,
|
|
||||||
maximum_addable_quantity: maximum,
|
|
||||||
values: { size: { value: 'M', label: 'Medium' } },
|
|
||||||
},
|
|
||||||
];
|
|
||||||
const emittedIds: Array<number | null> = [];
|
|
||||||
fixture.componentInstance.variantChange.subscribe((variant) =>
|
|
||||||
emittedIds.push(variant?.id ?? null),
|
|
||||||
);
|
|
||||||
fixture.componentRef.setInput('attributes', [sizeAttribute]);
|
|
||||||
fixture.componentRef.setInput('inventoryPolicy', maximum === null ? 'unlimited' : 'tracked');
|
|
||||||
fixture.componentRef.setInput('variants', variants);
|
|
||||||
fixture.componentRef.setInput('selectedVariant', variants[0]);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
const buttons = fixture.nativeElement.querySelectorAll(
|
|
||||||
'.attribute-selector__text-option',
|
|
||||||
) as NodeListOf<HTMLButtonElement>;
|
|
||||||
expect(buttons[1].disabled).toBe(maximum === 0);
|
|
||||||
buttons[1].click();
|
|
||||||
fixture.detectChanges();
|
|
||||||
expect(emittedIds.at(-1)).toBe(maximum === 0 ? 1 : 2);
|
|
||||||
expect(buttons[0].disabled).toBe(false);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
it('keeps an unlimited option available when maximum quantity is null', () => {
|
it('keeps an unlimited option available when maximum quantity is null', () => {
|
||||||
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
||||||
fixture.componentRef.setInput('attributes', [sizeAttribute]);
|
fixture.componentRef.setInput('attributes', [sizeAttribute]);
|
||||||
@@ -91,7 +32,7 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
maximum_addable_quantity: null,
|
availability: createCatalogAvailability(null),
|
||||||
values: { size: 'S' },
|
values: { size: 'S' },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -111,12 +52,12 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
maximum_addable_quantity: 0,
|
availability: createCatalogAvailability(0),
|
||||||
values: { size: 'S' },
|
values: { size: 'S' },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
maximum_addable_quantity: 2,
|
availability: createCatalogAvailability(2),
|
||||||
values: { size: 'M' },
|
values: { size: 'M' },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -152,18 +93,9 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
]);
|
]);
|
||||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{ id: 1, maximum_addable_quantity: null, values: { event_date: '1' } },
|
{ id: 1, availability: createCatalogAvailability(null), values: { event_date: '1' } },
|
||||||
{ id: 2, maximum_addable_quantity: null, values: { event_date: '2' } },
|
{ id: 2, availability: createCatalogAvailability(null), values: { event_date: '2' } },
|
||||||
{
|
{ id: 3, availability: createCatalogAvailability(null), values: { event_date: ['1', '2'] } },
|
||||||
id: 3,
|
|
||||||
maximum_addable_quantity: null,
|
|
||||||
values: {
|
|
||||||
event_date: [
|
|
||||||
{ value: '1', label: '09/10/2026' },
|
|
||||||
{ value: '2', label: '10/10/2026' },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
]);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
@@ -204,8 +136,16 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
]);
|
]);
|
||||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{ id: 1, maximum_addable_quantity: null, values: { size: 'S', internal_type: 'adult' } },
|
{
|
||||||
{ id: 2, maximum_addable_quantity: null, values: { size: 'M', internal_type: 'child' } },
|
id: 1,
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
|
values: { size: 'S', internal_type: 'adult' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
|
values: { size: 'M', internal_type: 'child' },
|
||||||
|
},
|
||||||
]);
|
]);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
ProductAttribute,
|
ProductAttribute,
|
||||||
ProductAttributeOption,
|
ProductAttributeOption,
|
||||||
} from '../../../../core/services/catalog/catalog.interface';
|
} from '../../../../core/services/catalog/catalog.interface';
|
||||||
|
import { allowsCatalogAction } from '../../../../core/services/catalog/catalog-availability';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-attribute-selector',
|
selector: 'app-product-attribute-selector',
|
||||||
@@ -29,6 +30,7 @@ export class ProductAttributeSelectorComponent {
|
|||||||
public variants = input<CatalogItemVariant[]>([]);
|
public variants = input<CatalogItemVariant[]>([]);
|
||||||
public selectedVariant = input<CatalogItemVariant | null>(null);
|
public selectedVariant = input<CatalogItemVariant | null>(null);
|
||||||
public inventoryPolicy = input.required<InventoryPolicy>();
|
public inventoryPolicy = input.required<InventoryPolicy>();
|
||||||
|
public disabled = input(false);
|
||||||
|
|
||||||
public variantChange = output<CatalogItemVariant | null>();
|
public variantChange = output<CatalogItemVariant | null>();
|
||||||
|
|
||||||
@@ -55,11 +57,11 @@ export class ProductAttributeSelectorComponent {
|
|||||||
if (!this.isVariantAvailable(variant)) return false;
|
if (!this.isVariantAvailable(variant)) return false;
|
||||||
|
|
||||||
const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values);
|
const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values);
|
||||||
const desiredOptionIds = !attribute.allow_multi_select
|
const desiredOptionIds = attribute.allow_multi_select
|
||||||
? [option.id]
|
? selectedForAttribute.includes(option.id)
|
||||||
: selectedForAttribute.includes(option.id)
|
|
||||||
? selectedForAttribute
|
? selectedForAttribute
|
||||||
: [...selectedForAttribute, option.id];
|
: [...selectedForAttribute, option.id]
|
||||||
|
: [option.id];
|
||||||
const desiredValues = desiredOptionIds
|
const desiredValues = desiredOptionIds
|
||||||
.map((id) => attribute.options.find((candidate) => candidate.id === id))
|
.map((id) => attribute.options.find((candidate) => candidate.id === id))
|
||||||
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
|
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
|
||||||
@@ -130,6 +132,8 @@ export class ProductAttributeSelectorComponent {
|
|||||||
attribute: ProductAttribute,
|
attribute: ProductAttribute,
|
||||||
option: ProductAttributeOption,
|
option: ProductAttributeOption,
|
||||||
): void {
|
): void {
|
||||||
|
if (this.disabled()) return;
|
||||||
|
|
||||||
this.selectedAttributeOptions.update((current) => {
|
this.selectedAttributeOptions.update((current) => {
|
||||||
const selected = current[attribute.codigo] ?? [];
|
const selected = current[attribute.codigo] ?? [];
|
||||||
const isMultiple = attribute.allow_multi_select ?? false;
|
const isMultiple = attribute.allow_multi_select ?? false;
|
||||||
@@ -179,7 +183,15 @@ export class ProductAttributeSelectorComponent {
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultValues = this.getVariantAttributeValues(attribute, variant.values);
|
const defaultValues =
|
||||||
|
attribute.type === 'event_date'
|
||||||
|
? (
|
||||||
|
variant.event_date_ids ??
|
||||||
|
(variant.event_date_id === null || variant.event_date_id === undefined
|
||||||
|
? []
|
||||||
|
: [variant.event_date_id])
|
||||||
|
).map(String)
|
||||||
|
: this.getVariantAttributeValues(attribute, variant.values);
|
||||||
if (defaultValues.length === 0) {
|
if (defaultValues.length === 0) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
@@ -195,7 +207,7 @@ export class ProductAttributeSelectorComponent {
|
|||||||
|
|
||||||
private getVariantAttributeValues(
|
private getVariantAttributeValues(
|
||||||
attribute: ProductAttribute,
|
attribute: ProductAttribute,
|
||||||
variantAttributes: CatalogItemVariant['values'],
|
variantAttributes: Record<string, string | string[]>,
|
||||||
): string[] {
|
): string[] {
|
||||||
const normalizedCodigo = this.normalizeText(attribute.codigo);
|
const normalizedCodigo = this.normalizeText(attribute.codigo);
|
||||||
const normalizedNombre = this.normalizeText(attribute.nombre);
|
const normalizedNombre = this.normalizeText(attribute.nombre);
|
||||||
@@ -204,12 +216,21 @@ export class ProductAttributeSelectorComponent {
|
|||||||
const normalizedKey = this.normalizeText(key);
|
const normalizedKey = this.normalizeText(key);
|
||||||
|
|
||||||
if (normalizedKey === normalizedCodigo || normalizedKey === normalizedNombre) {
|
if (normalizedKey === normalizedCodigo || normalizedKey === normalizedNombre) {
|
||||||
return (Array.isArray(value) ? value : [value]).map((item) =>
|
return (Array.isArray(value) ? value : [value]).map((item) => this.normalizeText(item));
|
||||||
this.normalizeText(typeof item === 'string' ? item : item.value || item.label),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (attribute.type === 'event_date') {
|
||||||
|
const variant = this.variants().find((candidate) => candidate.values === variantAttributes);
|
||||||
|
const eventDateIds =
|
||||||
|
variant?.event_date_ids ??
|
||||||
|
(variant?.event_date_id === null || variant?.event_date_id === undefined
|
||||||
|
? []
|
||||||
|
: [variant.event_date_id]);
|
||||||
|
|
||||||
|
return eventDateIds.map(String);
|
||||||
|
}
|
||||||
|
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,7 +243,7 @@ export class ProductAttributeSelectorComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
||||||
return variant.maximum_addable_quantity !== 0;
|
return allowsCatalogAction(variant.availability, 'select_variant');
|
||||||
}
|
}
|
||||||
|
|
||||||
private findFirstHexValue(value: unknown): string | null {
|
private findFirstHexValue(value: unknown): string | null {
|
||||||
|
|||||||
@@ -54,7 +54,7 @@
|
|||||||
<!-- Thumbnails Row -->
|
<!-- Thumbnails Row -->
|
||||||
@if (images().length > 1) {
|
@if (images().length > 1) {
|
||||||
<div class="product-carousel__thumbnails">
|
<div class="product-carousel__thumbnails">
|
||||||
@for (image of images(); track $index; let idx = $index) {
|
@for (image of images(); track image; let idx = $index) {
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="product-carousel__thumbnail border-0 p-0 overflow-hidden bg-light"
|
class="product-carousel__thumbnail border-0 p-0 overflow-hidden bg-light"
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ export interface TicketResponse {
|
|||||||
starts_at: string | null;
|
starts_at: string | null;
|
||||||
expires_at: string | null;
|
expires_at: string | null;
|
||||||
used_at: string | null;
|
used_at: string | null;
|
||||||
status?: 'active' | 'expired' | 'used' | 'disabled' | 'cancelled' | 'refunded';
|
|
||||||
status_label?: string;
|
|
||||||
is_valid: boolean;
|
is_valid: boolean;
|
||||||
is_expired: boolean;
|
is_expired: boolean;
|
||||||
is_used: boolean;
|
is_used: boolean;
|
||||||
@@ -28,7 +26,9 @@ export class TicketService extends BaseApiService {
|
|||||||
|
|
||||||
getTickets(): Promise<TicketResponse[]> {
|
getTickets(): Promise<TicketResponse[]> {
|
||||||
return firstValueFrom(
|
return firstValueFrom(
|
||||||
this.http.get<{ data: TicketResponse[] }>(`${this.tenantService.getTenantApiUrl()}/tickets`),
|
this.http.get<{ data: TicketResponse[] }>(
|
||||||
|
`${this.tenantService.getTenantApiUrl()}/tickets`,
|
||||||
|
),
|
||||||
).then((response) => response.data ?? []);
|
).then((response) => response.data ?? []);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -63,11 +63,7 @@ export class TicketsPage implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected isInactive(ticket: TicketResponse): boolean {
|
protected isInactive(ticket: TicketResponse): boolean {
|
||||||
return (
|
return ticket.is_expired || ticket.is_used;
|
||||||
(ticket.status !== undefined && ticket.status !== 'active') ||
|
|
||||||
ticket.is_expired ||
|
|
||||||
ticket.is_used
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected formatDate(ticket: TicketResponse): string | null {
|
protected formatDate(ticket: TicketResponse): string | null {
|
||||||
|
|||||||
@@ -23,10 +23,7 @@ import {
|
|||||||
|
|
||||||
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 {
|
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||||
CheckoutService,
|
|
||||||
isExpiredStockReservationResponse,
|
|
||||||
} from '../../../../core/services/checkout.service';
|
|
||||||
import {
|
import {
|
||||||
CatalogGroupLayout,
|
CatalogGroupLayout,
|
||||||
CategoryItemsResponse,
|
CategoryItemsResponse,
|
||||||
@@ -170,20 +167,10 @@ export class CategoryItemsPageComponent {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
await this.router.navigate(['/checkout', 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);
|
||||||
const message =
|
this.toastService.danger('No se pudo iniciar la compra directa.');
|
||||||
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
|
||||||
? error.error.message
|
|
||||||
: 'No se pudo iniciar la compra directa.';
|
|
||||||
this.toastService.danger(message);
|
|
||||||
|
|
||||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
|
||||||
this.cartService.loadCart(true).subscribe({
|
|
||||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
this.creatingDirectPurchase.set(false);
|
this.creatingDirectPurchase.set(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,7 +34,6 @@
|
|||||||
[qrPaymentAmount]="cartTotal()"
|
[qrPaymentAmount]="cartTotal()"
|
||||||
[whatsappUrl]="whatsappUrl()"
|
[whatsappUrl]="whatsappUrl()"
|
||||||
[transferValidationStatus]="transferValidationStatus()"
|
[transferValidationStatus]="transferValidationStatus()"
|
||||||
[transferVerificationErrorTitle]="transferVerificationErrorTitle()"
|
|
||||||
(paymentMethodChange)="selectPaymentMethod($event)"
|
(paymentMethodChange)="selectPaymentMethod($event)"
|
||||||
(copyTransferValue)="copyTransferValue($event.field, $event.value)"
|
(copyTransferValue)="copyTransferValue($event.field, $event.value)"
|
||||||
(cancelStep)="onCancel()"
|
(cancelStep)="onCancel()"
|
||||||
@@ -47,17 +46,6 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="checkout-page__cart-col">
|
<div class="checkout-page__cart-col">
|
||||||
@if (checkoutRemainingTime(); as remainingTime) {
|
|
||||||
<div
|
|
||||||
class="checkout-page__mobile-countdown d-flex d-md-none align-items-baseline justify-content-center gap-3"
|
|
||||||
role="timer"
|
|
||||||
aria-label="Tiempo restante de compra"
|
|
||||||
>
|
|
||||||
<span class="checkout-page__mobile-countdown-label">Tiempo restante de compra:</span>
|
|
||||||
<span class="checkout-page__mobile-countdown-value">{{ remainingTime }}</span>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
<app-cart
|
<app-cart
|
||||||
title="COMPRA"
|
title="COMPRA"
|
||||||
[items]="mappedCartItems()"
|
[items]="mappedCartItems()"
|
||||||
|
|||||||
@@ -28,24 +28,6 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
&__mobile-countdown {
|
|
||||||
flex: 0 0 auto;
|
|
||||||
margin-bottom: 1.5rem;
|
|
||||||
color: var(--tenant-primary);
|
|
||||||
font-weight: 700;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
&__mobile-countdown-label {
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
|
|
||||||
&__mobile-countdown-value {
|
|
||||||
font-size: 20px;
|
|
||||||
line-height: 1;
|
|
||||||
font-variant-numeric: tabular-nums;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.checkout-page__loading {
|
.checkout-page__loading {
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import { TenantService } from '../../../../core/services/tenant.service';
|
|||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
|
import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
|
||||||
import { CheckoutCountdownService } from '../../../../core/services/checkout-countdown.service';
|
|
||||||
import { CheckoutPageComponent } from './checkout-page.component';
|
import { CheckoutPageComponent } from './checkout-page.component';
|
||||||
|
|
||||||
describe('CheckoutPageComponent payment validation', () => {
|
describe('CheckoutPageComponent payment validation', () => {
|
||||||
@@ -34,7 +33,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
stop: ReturnType<typeof vi.fn>;
|
stop: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
let cartServiceStub: { loadCart: ReturnType<typeof vi.fn> };
|
let cartServiceStub: { loadCart: ReturnType<typeof vi.fn> };
|
||||||
let routeParamMap: ReturnType<typeof convertToParamMap>;
|
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
|
||||||
let authUserState: ReturnType<typeof signal>;
|
let authUserState: ReturnType<typeof signal>;
|
||||||
let tenantState: ReturnType<
|
let tenantState: ReturnType<
|
||||||
typeof signal<{
|
typeof signal<{
|
||||||
@@ -77,7 +76,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
cartServiceStub = {
|
cartServiceStub = {
|
||||||
loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })),
|
loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })),
|
||||||
};
|
};
|
||||||
routeParamMap = convertToParamMap({});
|
routeQueryParamMap = convertToParamMap({});
|
||||||
authUserState = signal(null);
|
authUserState = signal(null);
|
||||||
tenantState = signal({
|
tenantState = signal({
|
||||||
codigo: 'tenant-test',
|
codigo: 'tenant-test',
|
||||||
@@ -104,8 +103,8 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
useValue: {
|
useValue: {
|
||||||
snapshot: {
|
snapshot: {
|
||||||
get paramMap() {
|
get queryParamMap() {
|
||||||
return routeParamMap;
|
return routeQueryParamMap;
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -130,93 +129,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
return { fixture, component: fixture.componentInstance as any };
|
return { fixture, component: fixture.componentInstance as any };
|
||||||
}
|
}
|
||||||
|
|
||||||
it('does not expose an active countdown until the purchase timing is loaded', async () => {
|
|
||||||
const countdown = TestBed.inject(CheckoutCountdownService);
|
|
||||||
countdown.synchronize({
|
|
||||||
expires_at: null,
|
|
||||||
expires_in_seconds: 600,
|
|
||||||
server_time: new Date().toISOString(),
|
|
||||||
});
|
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
|
||||||
id: 25,
|
|
||||||
status: 'created',
|
|
||||||
expires_at: '2026-08-27T15:10:00.000Z',
|
|
||||||
expires_in_seconds: 600,
|
|
||||||
server_time: '2026-08-27T15:00:00.000Z',
|
|
||||||
items: [],
|
|
||||||
subtotal: '0.00',
|
|
||||||
total: '0.00',
|
|
||||||
});
|
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
|
||||||
|
|
||||||
const { component } = createComponent();
|
|
||||||
|
|
||||||
expect(component.checkoutRemainingTime()).toBeNull();
|
|
||||||
|
|
||||||
await Promise.resolve();
|
|
||||||
|
|
||||||
expect(countdown.remainingSeconds()).toBe(600);
|
|
||||||
expect(component.checkoutRemainingTime()).toBe('10:00');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('checks the purchase when the countdown expires and redirects to the expired status', async () => {
|
|
||||||
const countdown = TestBed.inject(CheckoutCountdownService);
|
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'expired' });
|
|
||||||
const { fixture, component } = createComponent();
|
|
||||||
component.createdPurchase.set({
|
|
||||||
id: 25,
|
|
||||||
status: 'created',
|
|
||||||
expires_at: new Date(Date.now() + 1_000).toISOString(),
|
|
||||||
expires_in_seconds: 1,
|
|
||||||
server_time: new Date().toISOString(),
|
|
||||||
items: [],
|
|
||||||
subtotal: '0.00',
|
|
||||||
total: '0.00',
|
|
||||||
});
|
|
||||||
countdown.synchronize(component.createdPurchase());
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(1_000);
|
|
||||||
fixture.detectChanges();
|
|
||||||
await Promise.resolve();
|
|
||||||
|
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledOnce();
|
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
|
||||||
queryParams: { status: 'expired' },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('checks the purchase only once when the expired countdown remains at zero', async () => {
|
|
||||||
const countdown = TestBed.inject(CheckoutCountdownService);
|
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
|
||||||
status: 'pending_payment',
|
|
||||||
expires_at: new Date(Date.now() - 1_000).toISOString(),
|
|
||||||
expires_in_seconds: 0,
|
|
||||||
server_time: new Date().toISOString(),
|
|
||||||
});
|
|
||||||
const { fixture, component } = createComponent();
|
|
||||||
component.createdPurchase.set({
|
|
||||||
id: 25,
|
|
||||||
status: 'pending_payment',
|
|
||||||
expires_at: new Date(Date.now() - 1_000).toISOString(),
|
|
||||||
expires_in_seconds: 0,
|
|
||||||
server_time: new Date().toISOString(),
|
|
||||||
items: [],
|
|
||||||
subtotal: '0.00',
|
|
||||||
total: '0.00',
|
|
||||||
});
|
|
||||||
countdown.synchronize(component.createdPurchase());
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
await Promise.resolve();
|
|
||||||
fixture.detectChanges();
|
|
||||||
await vi.advanceTimersByTimeAsync(5_000);
|
|
||||||
|
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledOnce();
|
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('polls QR after five seconds and navigates only when payment is paid', async () => {
|
it('polls QR after five seconds and navigates only when payment is paid', async () => {
|
||||||
checkoutServiceStub.getPurchase
|
checkoutServiceStub.getPurchase
|
||||||
.mockResolvedValueOnce({ status: 'pending_payment' })
|
.mockResolvedValueOnce({ status: 'pending_payment' })
|
||||||
@@ -283,7 +195,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('polls a transfer every three seconds for one minute', async () => {
|
it('polls a transfer every three seconds up to four attempts', async () => {
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
|
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
@@ -293,12 +205,14 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(57_000);
|
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(19);
|
await vi.advanceTimersByTimeAsync(3_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(attempt);
|
||||||
expect(component.transferValidationStatus()).toBe('checking');
|
expect(component.transferValidationStatus()).toBe('checking');
|
||||||
|
}
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(3_000);
|
await vi.advanceTimersByTimeAsync(3_000);
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
@@ -342,43 +256,13 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
await component.onComplete();
|
await component.onComplete();
|
||||||
await vi.advanceTimersByTimeAsync(60_000);
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uses the primary candidate reason when transfer polling times out', async () => {
|
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
|
||||||
status: 'in_review',
|
|
||||||
payment_verification: {
|
|
||||||
status: 'candidate',
|
|
||||||
candidate_count: 1,
|
|
||||||
primary: {
|
|
||||||
reason: 'exact_amount_near_dni',
|
|
||||||
dni_distance: 1,
|
|
||||||
payment_amount: '300000.00',
|
|
||||||
purchase_amount: '300000.00',
|
|
||||||
amount_difference: '0.00',
|
|
||||||
confidence: 'medium',
|
|
||||||
detected_at: '2026-08-27T18:00:00-03:00',
|
|
||||||
},
|
|
||||||
reasons: ['exact_amount_near_dni'],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const { component } = createComponent();
|
|
||||||
component.selectedPaymentMethod.set('transfer');
|
|
||||||
|
|
||||||
await component.onComplete();
|
|
||||||
await vi.advanceTimersByTimeAsync(60_000);
|
|
||||||
|
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
|
||||||
expect(component.transferVerificationErrorTitle()).toBe(
|
|
||||||
'El DNI no corresponde con el de la transferencia',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not poll when submitting a transfer for review fails', async () => {
|
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'));
|
||||||
@@ -433,7 +317,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
subtotal: '2501.00',
|
subtotal: '2501.00',
|
||||||
total: '2501.00',
|
total: '2501.00',
|
||||||
};
|
};
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue(purchase);
|
checkoutServiceStub.getPurchase.mockResolvedValue(purchase);
|
||||||
authUserState.set({
|
authUserState.set({
|
||||||
id: 7,
|
id: 7,
|
||||||
@@ -470,7 +354,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
|
|
||||||
it('keeps the checkout hidden while the purchase is loading', async () => {
|
it('keeps the checkout hidden while the purchase is loading', async () => {
|
||||||
let resolvePurchase!: (purchase: any) => void;
|
let resolvePurchase!: (purchase: any) => void;
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockReturnValue(
|
checkoutServiceStub.getPurchase.mockReturnValue(
|
||||||
new Promise((resolve) => {
|
new Promise((resolve) => {
|
||||||
resolvePurchase = resolve;
|
resolvePurchase = resolve;
|
||||||
@@ -491,13 +375,12 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
});
|
});
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
|
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
|
||||||
expect(component.isLoadingPurchase()).toBe(false);
|
expect(component.isLoadingPurchase()).toBe(false);
|
||||||
expect(component.checkoutStepIndex()).toBe(0);
|
expect(component.checkoutStepIndex()).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('opens a pending purchase on the payment step and restores its payment method', async () => {
|
it('opens a pending purchase on the payment step and restores its payment method', async () => {
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status: 'pending_payment',
|
status: 'pending_payment',
|
||||||
@@ -517,7 +400,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('generates a new QR when reopening a pending QR purchase', async () => {
|
it('generates a new QR when reopening a pending QR purchase', async () => {
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status: 'pending_payment',
|
status: 'pending_payment',
|
||||||
@@ -541,7 +424,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
it.each(['paid', 'cancelled', 'rejected', 'expired'])(
|
it.each(['paid', 'cancelled', 'rejected', 'expired'])(
|
||||||
'redirects a %s purchase to its status page',
|
'redirects a %s purchase to its status page',
|
||||||
async (status) => {
|
async (status) => {
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status,
|
status,
|
||||||
@@ -559,7 +442,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
it('redirects a submitted pending payment purchase to its status page', async () => {
|
it('redirects a submitted pending payment purchase to its status page', async () => {
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status: 'pending_payment',
|
status: 'pending_payment',
|
||||||
@@ -577,7 +460,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the API error and redirects to status when cancellation finds an expired purchase', async () => {
|
it('shows the API error in a toast when cancelling the purchase fails', async () => {
|
||||||
const message = 'La compra venció. Iniciá una nueva compra.';
|
const message = 'La compra venció. Iniciá una nueva compra.';
|
||||||
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
||||||
error: { code: 'purchase.expired', message },
|
error: { code: 'purchase.expired', message },
|
||||||
@@ -587,9 +470,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
await component.onModifyPurchase();
|
await component.onModifyPurchase();
|
||||||
|
|
||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
queryParams: { status: 'expired' },
|
|
||||||
});
|
|
||||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
||||||
expect(component.isCancellingPurchase()).toBe(false);
|
expect(component.isCancellingPurchase()).toBe(false);
|
||||||
@@ -706,24 +587,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(component.createdPurchaseId()).toBe(25);
|
expect(component.createdPurchaseId()).toBe(25);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('allows leaving checkout when cancellation finds an expired stock reservation', async () => {
|
it('shows the API message and redirects home when a checkout operation finds an expired purchase', async () => {
|
||||||
const message = 'La reserva de stock venció. Usá el carrito activo para continuar.';
|
|
||||||
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
|
||||||
error: { code: 'stock_reservation.expired', message },
|
|
||||||
});
|
|
||||||
const { component } = createComponent();
|
|
||||||
|
|
||||||
await expect(component.canDeactivate()).resolves.toBe(true);
|
|
||||||
|
|
||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
|
|
||||||
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
|
|
||||||
expect(component.createdPurchaseId()).toBeNull();
|
|
||||||
expect(component.createdPurchase()).toBeNull();
|
|
||||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
|
||||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows the API message and redirects to status when a checkout operation finds an expired purchase', async () => {
|
|
||||||
checkoutServiceStub.generatePaymentIntent.mockRejectedValue(
|
checkoutServiceStub.generatePaymentIntent.mockRejectedValue(
|
||||||
new HttpErrorResponse({
|
new HttpErrorResponse({
|
||||||
status: 422,
|
status: 422,
|
||||||
@@ -740,35 +604,10 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
);
|
);
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/']);
|
||||||
queryParams: { status: 'expired' },
|
|
||||||
});
|
|
||||||
expect(component.isGeneratingIntent()).toBe(false);
|
expect(component.isGeneratingIntent()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('redirects to status when QR polling receives a purchase-expired response', async () => {
|
|
||||||
checkoutServiceStub.getPurchase.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');
|
|
||||||
await vi.advanceTimersByTimeAsync(5_000);
|
|
||||||
|
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
|
||||||
queryParams: { status: 'expired' },
|
|
||||||
});
|
|
||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
|
||||||
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('treats a generic customer-data error as expired when the local deadline passed', () => {
|
it('treats a generic customer-data error as expired when the local deadline passed', () => {
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
component.createdPurchase.set({
|
component.createdPurchase.set({
|
||||||
@@ -796,8 +635,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
);
|
);
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/']);
|
||||||
queryParams: { status: 'expired' },
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import {
|
|||||||
ChangeDetectionStrategy,
|
ChangeDetectionStrategy,
|
||||||
Component,
|
Component,
|
||||||
computed,
|
computed,
|
||||||
effect,
|
|
||||||
inject,
|
inject,
|
||||||
OnDestroy,
|
OnDestroy,
|
||||||
OnInit,
|
OnInit,
|
||||||
@@ -17,10 +16,8 @@ import { firstValueFrom, startWith } from 'rxjs';
|
|||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import {
|
import {
|
||||||
CheckoutService,
|
CheckoutService,
|
||||||
PurchasePaymentCandidateReason,
|
|
||||||
PurchaseDetailItemResponse,
|
PurchaseDetailItemResponse,
|
||||||
PurchaseDetailResponse,
|
PurchaseDetailResponse,
|
||||||
PurchaseStatusResponse,
|
|
||||||
} 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 { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
|
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
|
||||||
@@ -31,7 +28,6 @@ import { StepComponent } from '../../../../shared/components/stepper/step.compon
|
|||||||
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
||||||
import { CheckoutDataStepComponent } from './checkout-data-step.component';
|
import { CheckoutDataStepComponent } from './checkout-data-step.component';
|
||||||
import { CheckoutPaymentStepComponent } from './checkout-payment-step.component';
|
import { CheckoutPaymentStepComponent } from './checkout-payment-step.component';
|
||||||
import { CheckoutCountdownService } from '../../../../core/services/checkout-countdown.service';
|
|
||||||
import {
|
import {
|
||||||
CheckoutForm,
|
CheckoutForm,
|
||||||
PaymentMethod,
|
PaymentMethod,
|
||||||
@@ -68,7 +64,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
|
|
||||||
private readonly authService = inject(AuthService);
|
private readonly authService = inject(AuthService);
|
||||||
private readonly globalLoadingService = inject(GlobalLoadingService);
|
private readonly globalLoadingService = inject(GlobalLoadingService);
|
||||||
private readonly toastService = inject(ToastService);
|
private readonly toastService = inject(ToastService);
|
||||||
@@ -76,7 +71,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
private readonly qrPollingIntervalMs = 5_000;
|
private readonly qrPollingIntervalMs = 5_000;
|
||||||
private readonly qrPollingMaxAttempts = 120;
|
private readonly qrPollingMaxAttempts = 120;
|
||||||
private readonly transferPollingIntervalMs = 3_000;
|
private readonly transferPollingIntervalMs = 3_000;
|
||||||
private readonly transferPollingMaxAttempts = 20;
|
private readonly transferPollingMaxAttempts = 209;
|
||||||
|
|
||||||
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
private qrPollingAttempts = 0;
|
private qrPollingAttempts = 0;
|
||||||
@@ -87,7 +82,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
private paymentMethodRequestId = 0;
|
private paymentMethodRequestId = 0;
|
||||||
private navigationStarted = false;
|
private navigationStarted = false;
|
||||||
private cancelPurchasePromise: Promise<boolean> | null = null;
|
private cancelPurchasePromise: Promise<boolean> | null = null;
|
||||||
private expirationCheckPurchaseId: number | null = null;
|
|
||||||
|
|
||||||
@ViewChild(StepperComponent) stepper!: StepperComponent;
|
@ViewChild(StepperComponent) stepper!: StepperComponent;
|
||||||
|
|
||||||
@@ -101,27 +95,6 @@ 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 checkoutRemainingTime = computed(() => {
|
|
||||||
const purchase = this.createdPurchase();
|
|
||||||
|
|
||||||
if (
|
|
||||||
!purchase ||
|
|
||||||
(typeof purchase.expires_at !== 'string' && typeof purchase.expires_in_seconds !== 'number')
|
|
||||||
) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const remainingSeconds = this.checkoutCountdownService.remainingSeconds();
|
|
||||||
|
|
||||||
if (remainingSeconds === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const minutes = Math.floor(remainingSeconds / 60);
|
|
||||||
const seconds = remainingSeconds % 60;
|
|
||||||
|
|
||||||
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
|
||||||
});
|
|
||||||
protected readonly cartSubtotal = computed(() => {
|
protected readonly cartSubtotal = computed(() => {
|
||||||
const purchase = this.createdPurchase();
|
const purchase = this.createdPurchase();
|
||||||
return purchase ? parseFloat(purchase.subtotal) : 0;
|
return purchase ? parseFloat(purchase.subtotal) : 0;
|
||||||
@@ -162,14 +135,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
|
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
|
||||||
protected readonly isCheckingQrPayment = signal(false);
|
protected readonly isCheckingQrPayment = signal(false);
|
||||||
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
|
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
|
||||||
private readonly transferPrimaryCandidateReason = signal<PurchasePaymentCandidateReason | null>(
|
|
||||||
null,
|
|
||||||
);
|
|
||||||
protected readonly transferVerificationErrorTitle = computed(() =>
|
|
||||||
this.transferPrimaryCandidateReason() === 'exact_amount_near_dni'
|
|
||||||
? 'El DNI no corresponde con el de la transferencia'
|
|
||||||
: null,
|
|
||||||
);
|
|
||||||
protected readonly whatsappUrl = computed(
|
protected readonly whatsappUrl = computed(
|
||||||
() =>
|
() =>
|
||||||
this.tenantService
|
this.tenantService
|
||||||
@@ -178,28 +143,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
);
|
);
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
effect(() => {
|
|
||||||
const remainingSeconds = this.checkoutCountdownService.remainingSeconds();
|
|
||||||
const purchaseId = this.createdPurchaseId() ?? this.createdPurchase()?.id ?? null;
|
|
||||||
|
|
||||||
if (remainingSeconds !== null && remainingSeconds > 0) {
|
|
||||||
this.expirationCheckPurchaseId = null;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
remainingSeconds !== 0 ||
|
|
||||||
purchaseId === null ||
|
|
||||||
this.navigationStarted ||
|
|
||||||
this.expirationCheckPurchaseId === purchaseId
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.expirationCheckPurchaseId = purchaseId;
|
|
||||||
void this.checkPurchaseAfterCountdownExpiration(purchaseId);
|
|
||||||
});
|
|
||||||
|
|
||||||
this.form.statusChanges
|
this.form.statusChanges
|
||||||
.pipe(startWith(this.form.status))
|
.pipe(startWith(this.form.status))
|
||||||
.subscribe(() => this.isStep1Valid.set(this.form.valid));
|
.subscribe(() => this.isStep1Valid.set(this.form.valid));
|
||||||
@@ -218,7 +161,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
const purchaseId = Number(this.route.snapshot.paramMap.get('id'));
|
const purchaseId = Number(this.route.snapshot.queryParamMap.get('purchase'));
|
||||||
if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
|
if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
|
||||||
void this.router.navigate(['/']);
|
void this.router.navigate(['/']);
|
||||||
return;
|
return;
|
||||||
@@ -285,7 +228,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
nombre_apellido: formValue.nombre,
|
nombre_apellido: formValue.nombre,
|
||||||
});
|
});
|
||||||
this.createdPurchase.set(purchase);
|
this.createdPurchase.set(purchase);
|
||||||
this.checkoutCountdownService.synchronize(purchase);
|
|
||||||
|
|
||||||
this.stepper.next();
|
this.stepper.next();
|
||||||
|
|
||||||
@@ -339,7 +281,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
const tenant = this.tenantService.tenant();
|
const tenant = this.tenantService.tenant();
|
||||||
const purchaseId = this.createdPurchaseId();
|
const purchaseId = this.createdPurchaseId();
|
||||||
if (!tenant || !purchaseId) {
|
if (!tenant || !purchaseId) {
|
||||||
this.checkoutCountdownService.clear();
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,25 +291,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
await firstValueFrom(this.cartService.loadCart());
|
await firstValueFrom(this.cartService.loadCart());
|
||||||
this.createdPurchaseId.set(null);
|
this.createdPurchaseId.set(null);
|
||||||
this.createdPurchase.set(null);
|
this.createdPurchase.set(null);
|
||||||
this.checkoutCountdownService.clear();
|
|
||||||
|
|
||||||
this.navigationStarted = true;
|
this.navigationStarted = true;
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to cancel the current purchase:', error);
|
console.error('Failed to cancel the current purchase:', error);
|
||||||
|
|
||||||
if (this.isStockReservationExpiredError(error)) {
|
|
||||||
this.showRequestError(error, 'La reserva de stock venció.');
|
|
||||||
this.cartService.loadCart(true).subscribe({
|
|
||||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
|
||||||
});
|
|
||||||
this.createdPurchaseId.set(null);
|
|
||||||
this.createdPurchase.set(null);
|
|
||||||
this.checkoutCountdownService.clear();
|
|
||||||
this.navigationStarted = true;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.showRequestError(error, 'No se pudo cancelar la compra.');
|
this.showRequestError(error, 'No se pudo cancelar la compra.');
|
||||||
return false;
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -443,7 +370,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.transferDni.set(dni);
|
this.transferDni.set(dni);
|
||||||
this.stopTransferPolling();
|
this.stopTransferPolling();
|
||||||
this.transferValidationStatus.set('idle');
|
this.transferValidationStatus.set('idle');
|
||||||
this.transferPrimaryCandidateReason.set(null);
|
|
||||||
this.isGeneratingIntent.set(true);
|
this.isGeneratingIntent.set(true);
|
||||||
try {
|
try {
|
||||||
const response = await this.checkoutService
|
const response = await this.checkoutService
|
||||||
@@ -500,7 +426,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.stopTransferPolling();
|
this.stopTransferPolling();
|
||||||
this.hasSubmittedTransfer.set(true);
|
this.hasSubmittedTransfer.set(true);
|
||||||
this.transferValidationStatus.set('checking');
|
this.transferValidationStatus.set('checking');
|
||||||
this.transferPrimaryCandidateReason.set(null);
|
|
||||||
this.transferPollingAttempts = 0;
|
this.transferPollingAttempts = 0;
|
||||||
|
|
||||||
const runId = this.transferPollingRunId;
|
const runId = this.transferPollingRunId;
|
||||||
@@ -514,9 +439,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.checkoutCountdownService.synchronize(purchase);
|
|
||||||
this.captureTransferCandidateReason(purchase);
|
|
||||||
|
|
||||||
if (purchase.status === 'paid') {
|
if (purchase.status === 'paid') {
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
return;
|
return;
|
||||||
@@ -566,24 +488,12 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.checkoutCountdownService.synchronize(purchase);
|
|
||||||
this.captureTransferCandidateReason(purchase);
|
|
||||||
|
|
||||||
if (purchase.status === 'paid') {
|
if (purchase.status === 'paid') {
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (purchase.status === 'expired') {
|
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to validate transfer payment:', error);
|
console.error('Failed to validate transfer payment:', error);
|
||||||
if (this.isPurchaseExpiredError(error)) {
|
|
||||||
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (runId !== this.transferPollingRunId) {
|
if (runId !== this.transferPollingRunId) {
|
||||||
@@ -599,14 +509,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.scheduleTransferPoll(runId);
|
this.scheduleTransferPoll(runId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private captureTransferCandidateReason(purchase: PurchaseStatusResponse): void {
|
|
||||||
const reason = purchase.payment_verification?.primary?.reason;
|
|
||||||
|
|
||||||
if (reason) {
|
|
||||||
this.transferPrimaryCandidateReason.set(reason);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private stopTransferPolling(): void {
|
private stopTransferPolling(): void {
|
||||||
this.transferPollingRunId += 1;
|
this.transferPollingRunId += 1;
|
||||||
|
|
||||||
@@ -663,8 +565,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.checkoutCountdownService.synchronize(purchase);
|
|
||||||
|
|
||||||
if (purchase.status === 'paid') {
|
if (purchase.status === 'paid') {
|
||||||
this.handleConfirmedPayment(purchaseId);
|
this.handleConfirmedPayment(purchaseId);
|
||||||
return;
|
return;
|
||||||
@@ -675,17 +575,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.qrPaymentStatus.set('failed');
|
this.qrPaymentStatus.set('failed');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (purchase.status === 'expired') {
|
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to validate QR payment:', error);
|
console.error('Failed to validate QR payment:', error);
|
||||||
if (this.isPurchaseExpiredError(error)) {
|
|
||||||
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
if (runId === this.qrPollingRunId) {
|
if (runId === this.qrPollingRunId) {
|
||||||
this.isCheckingQrPayment.set(false);
|
this.isCheckingQrPayment.set(false);
|
||||||
@@ -738,40 +629,10 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.navigationStarted = true;
|
this.navigationStarted = true;
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
this.stopTransferPolling();
|
this.stopTransferPolling();
|
||||||
this.checkoutCountdownService.clear();
|
|
||||||
|
|
||||||
void this.router.navigate(['/checkout/status', purchaseId]);
|
void this.router.navigate(['/checkout/status', purchaseId]);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async checkPurchaseAfterCountdownExpiration(purchaseId: number): Promise<void> {
|
|
||||||
const tenant = this.tenantService.tenant();
|
|
||||||
|
|
||||||
if (!tenant || this.navigationStarted) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const purchase = await this.checkoutService
|
|
||||||
.withCustomLoading()
|
|
||||||
.getPurchase(tenant.codigo, purchaseId);
|
|
||||||
|
|
||||||
if (this.navigationStarted) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (purchase.status === 'expired') {
|
|
||||||
this.navigateToExpiredPurchaseStatus();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.checkoutCountdownService.synchronize(purchase);
|
|
||||||
} catch (error) {
|
|
||||||
if (this.isPurchaseExpiredError(error)) {
|
|
||||||
this.navigateToExpiredPurchaseStatus();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async loadPurchase(purchaseId: number): Promise<void> {
|
private async loadPurchase(purchaseId: number): Promise<void> {
|
||||||
const tenant = this.tenantService.tenant();
|
const tenant = this.tenantService.tenant();
|
||||||
if (!tenant) {
|
if (!tenant) {
|
||||||
@@ -805,7 +666,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
this.createdPurchaseId.set(purchase.id);
|
this.createdPurchaseId.set(purchase.id);
|
||||||
this.createdPurchase.set(purchase);
|
this.createdPurchase.set(purchase);
|
||||||
this.checkoutCountdownService.synchronize(purchase);
|
|
||||||
this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0);
|
this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
@@ -823,17 +683,15 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load purchase:', error);
|
console.error('Failed to load purchase:', error);
|
||||||
const expired = this.showRequestError(error, 'No se pudo cargar la compra.');
|
this.showRequestError(error, 'No se pudo cargar la compra.');
|
||||||
if (!expired) {
|
|
||||||
void this.router.navigate(['/']);
|
void this.router.navigate(['/']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private showRequestError(error: unknown, fallbackMessage: string): boolean {
|
private showRequestError(error: unknown, fallbackMessage: string): void {
|
||||||
const payload =
|
const payload =
|
||||||
typeof error === 'object' && error !== null && 'error' in error
|
typeof error === 'object' && error !== null && 'error' in error
|
||||||
? (error as { error?: ApiErrorResponse }).error
|
? (error as { error?: { message?: unknown } }).error
|
||||||
: undefined;
|
: undefined;
|
||||||
const message =
|
const message =
|
||||||
typeof payload?.message === 'string' && payload.message.trim()
|
typeof payload?.message === 'string' && payload.message.trim()
|
||||||
@@ -841,13 +699,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
: fallbackMessage;
|
: fallbackMessage;
|
||||||
|
|
||||||
this.toastService.danger(message);
|
this.toastService.danger(message);
|
||||||
|
|
||||||
if (payload?.code === 'purchase.expired') {
|
|
||||||
this.navigateToExpiredPurchaseStatus();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
|
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
|
||||||
@@ -866,7 +717,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
? response.message
|
? response.message
|
||||||
: 'La compra venció. Iniciá una nueva compra.',
|
: 'La compra venció. Iniciá una nueva compra.',
|
||||||
);
|
);
|
||||||
this.navigateToExpiredPurchaseStatus();
|
void this.router.navigate(['/']);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -878,43 +729,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private navigateToExpiredPurchaseStatus(): void {
|
|
||||||
const purchaseId = this.createdPurchaseId() ?? this.createdPurchase()?.id;
|
|
||||||
|
|
||||||
if (purchaseId) {
|
|
||||||
if (this.navigationStarted) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.navigationStarted = true;
|
|
||||||
this.stopQrPolling();
|
|
||||||
this.stopTransferPolling();
|
|
||||||
this.checkoutCountdownService.clear();
|
|
||||||
void this.router.navigate(['/checkout/status', purchaseId], {
|
|
||||||
queryParams: { status: 'expired' },
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
void this.router.navigate(['/']);
|
|
||||||
}
|
|
||||||
|
|
||||||
private isPurchaseExpiredError(error: unknown): boolean {
|
|
||||||
if (typeof error !== 'object' || error === null || !('error' in error)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (error as { error?: ApiErrorResponse }).error?.code === 'purchase.expired';
|
|
||||||
}
|
|
||||||
|
|
||||||
private isStockReservationExpiredError(error: unknown): boolean {
|
|
||||||
if (typeof error !== 'object' || error === null || !('error' in error)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (error as { error?: ApiErrorResponse }).error?.code === 'stock_reservation.expired';
|
|
||||||
}
|
|
||||||
|
|
||||||
private hasExpiredPurchase(): boolean {
|
private hasExpiredPurchase(): boolean {
|
||||||
const purchase = this.createdPurchase();
|
const purchase = this.createdPurchase();
|
||||||
|
|
||||||
|
|||||||
@@ -53,7 +53,6 @@
|
|||||||
[validationStatus]="transferValidationStatus()"
|
[validationStatus]="transferValidationStatus()"
|
||||||
[paymentAmount]="qrPaymentAmount()"
|
[paymentAmount]="qrPaymentAmount()"
|
||||||
[whatsappUrl]="whatsappUrl()"
|
[whatsappUrl]="whatsappUrl()"
|
||||||
[verificationErrorTitle]="transferVerificationErrorTitle()"
|
|
||||||
(copyTransferValue)="requestCopy($event.field, $event.value)"
|
(copyTransferValue)="requestCopy($event.field, $event.value)"
|
||||||
(submitDni)="generateTransferIntent.emit($event)"
|
(submitDni)="generateTransferIntent.emit($event)"
|
||||||
(completePurchase)="complete.emit()"
|
(completePurchase)="complete.emit()"
|
||||||
|
|||||||
@@ -33,7 +33,6 @@ export class CheckoutPaymentStepComponent {
|
|||||||
readonly qrPaymentAmount = input<number>(0);
|
readonly qrPaymentAmount = input<number>(0);
|
||||||
readonly whatsappUrl = input<string | null>(null);
|
readonly whatsappUrl = input<string | null>(null);
|
||||||
readonly transferValidationStatus = input<TransferValidationStatus>('idle');
|
readonly transferValidationStatus = input<TransferValidationStatus>('idle');
|
||||||
readonly transferVerificationErrorTitle = input<string | null>(null);
|
|
||||||
|
|
||||||
readonly paymentMethodChange = output<PaymentMethod>();
|
readonly paymentMethodChange = output<PaymentMethod>();
|
||||||
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
<app-payment-verification-error
|
<app-payment-verification-error
|
||||||
[paymentAmount]="paymentAmount()"
|
[paymentAmount]="paymentAmount()"
|
||||||
[whatsappUrl]="whatsappUrl()"
|
[whatsappUrl]="whatsappUrl()"
|
||||||
[title]="verificationErrorTitle()"
|
|
||||||
/>
|
/>
|
||||||
} @else {
|
} @else {
|
||||||
<div class="dni-form-container">
|
<div class="dni-form-container">
|
||||||
|
|||||||
@@ -47,23 +47,4 @@ describe('CheckoutPaymentTransferComponent', () => {
|
|||||||
expect(whatsapp).toBeDefined();
|
expect(whatsapp).toBeDefined();
|
||||||
expect(element.querySelector('.payment-verification')).toBeNull();
|
expect(element.querySelector('.payment-verification')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows a custom validation title for a near DNI candidate', async () => {
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [CheckoutPaymentTransferComponent],
|
|
||||||
}).compileComponents();
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
|
|
||||||
fixture.componentRef.setInput('validationStatus', 'error');
|
|
||||||
fixture.componentRef.setInput(
|
|
||||||
'verificationErrorTitle',
|
|
||||||
'El DNI no corresponde con el de la transferencia',
|
|
||||||
);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(fixture.nativeElement.textContent).toContain(
|
|
||||||
'El DNI no corresponde con el de la transferencia',
|
|
||||||
);
|
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('No pudimos verificar el pago de');
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ export class CheckoutPaymentTransferComponent implements OnInit {
|
|||||||
readonly validationStatus = input<TransferValidationStatus>('idle');
|
readonly validationStatus = input<TransferValidationStatus>('idle');
|
||||||
readonly paymentAmount = input<number>(0);
|
readonly paymentAmount = input<number>(0);
|
||||||
readonly whatsappUrl = input<string | null>(null);
|
readonly whatsappUrl = input<string | null>(null);
|
||||||
readonly verificationErrorTitle = input<string | null>(null);
|
|
||||||
|
|
||||||
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
||||||
readonly submitDni = output<string>();
|
readonly submitDni = output<string>();
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<div class="payment-timeout__icon" aria-hidden="true">
|
<div class="payment-timeout__icon" aria-hidden="true">
|
||||||
<i class="fa-solid fa-xmark"></i>
|
<i class="fa-solid fa-xmark"></i>
|
||||||
</div>
|
</div>
|
||||||
<h4 class="payment-timeout__title">{{ displayTitle() }}</h4>
|
<h4 class="payment-timeout__title">No pudimos verificar el pago de {{ formattedAmount() }}.</h4>
|
||||||
<p class="payment-timeout__message">Por favor contactate con nosotros para resolverlo.</p>
|
<p class="payment-timeout__message">Por favor contactate con nosotros para resolverlo.</p>
|
||||||
@if (whatsappUrl()) {
|
@if (whatsappUrl()) {
|
||||||
<app-button
|
<app-button
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import { ButtonComponent } from '../../../../../../shared/components/button/butt
|
|||||||
export class PaymentVerificationErrorComponent {
|
export class PaymentVerificationErrorComponent {
|
||||||
readonly paymentAmount = input<number>(0);
|
readonly paymentAmount = input<number>(0);
|
||||||
readonly whatsappUrl = input<string | null>(null);
|
readonly whatsappUrl = input<string | null>(null);
|
||||||
readonly title = input<string | null>(null);
|
|
||||||
|
|
||||||
protected readonly formattedAmount = computed(() =>
|
protected readonly formattedAmount = computed(() =>
|
||||||
new Intl.NumberFormat('es-AR', {
|
new Intl.NumberFormat('es-AR', {
|
||||||
@@ -22,9 +21,6 @@ export class PaymentVerificationErrorComponent {
|
|||||||
maximumFractionDigits: 0,
|
maximumFractionDigits: 0,
|
||||||
}).format(this.paymentAmount()),
|
}).format(this.paymentAmount()),
|
||||||
);
|
);
|
||||||
protected readonly displayTitle = computed(
|
|
||||||
() => this.title() ?? `No pudimos verificar el pago de ${this.formattedAmount()}.`,
|
|
||||||
);
|
|
||||||
|
|
||||||
protected openWhatsApp(): void {
|
protected openWhatsApp(): void {
|
||||||
const url = this.whatsappUrl();
|
const url = this.whatsappUrl();
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
@if (event(); as item) {
|
|
||||||
<div class="event-detail row gx-sm-4 gx-lg-5">
|
|
||||||
<aside class="event-detail__sidebar col-12 col-sm-4">
|
|
||||||
<div class="event-detail__image" [class.event-detail__image--placeholder]="!item.image">
|
|
||||||
@if (item.image) {
|
|
||||||
<img [src]="item.image" [alt]="item.title" />
|
|
||||||
} @else {
|
|
||||||
<span aria-hidden="true"><i class="fa-regular fa-calendar"></i></span>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
@if (item.starts_at) {
|
|
||||||
<app-counter-to [startsAt]="item.starts_at" />
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (item.description) {
|
|
||||||
<section class="event-detail__description" aria-labelledby="event-description-title">
|
|
||||||
<h2 id="event-description-title">Descripción</h2>
|
|
||||||
<p>{{ item.description }}</p>
|
|
||||||
</section>
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (item.social_media?.length) {
|
|
||||||
<section class="event-detail__social" aria-labelledby="event-social-title">
|
|
||||||
<h2 id="event-social-title">Información</h2>
|
|
||||||
@for (social of item.social_media; track social.code) {
|
|
||||||
<a [href]="social.url" target="_blank" rel="noopener noreferrer">
|
|
||||||
<i [class]="socialIcon(social.code)" aria-hidden="true"></i>
|
|
||||||
<span>{{ socialLabel(social.code) }}</span>
|
|
||||||
</a>
|
|
||||||
}
|
|
||||||
</section>
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (mapLocations().length) {
|
|
||||||
<app-location-map
|
|
||||||
class="event-detail__map"
|
|
||||||
[locations]="mapLocations()"
|
|
||||||
ariaLabel="Ubicación del evento"
|
|
||||||
mapStyle="minimal-light"
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
</aside>
|
|
||||||
|
|
||||||
<main class="event-detail__main col-12 col-sm-8">
|
|
||||||
<header class="event-detail__header">
|
|
||||||
<h1>{{ item.title }}</h1>
|
|
||||||
@if (item.subtitle) { <p class="event-detail__subtitle">{{ item.subtitle }}</p> }
|
|
||||||
<div class="event-detail__meta">
|
|
||||||
@if (item.date_text) {
|
|
||||||
<p><i class="fa-regular fa-calendar" aria-hidden="true"></i>
|
|
||||||
{{ item.date_text }}@if (item.dates?.length === 1 && item.start_time) { · {{ item.start_time.slice(0, 5) }} h }
|
|
||||||
</p>
|
|
||||||
}
|
|
||||||
@if (item.location) {
|
|
||||||
<p><i class="fa-solid fa-location-dot" aria-hidden="true"></i>{{ item.location }}</p>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<section class="event-detail__products" aria-labelledby="event-products-title">
|
|
||||||
<div class="event-detail__section-heading"><h2 id="event-products-title">Productos</h2></div>
|
|
||||||
|
|
||||||
@if ((item.dates?.length ?? 0) > 1) {
|
|
||||||
<label class="event-detail__date-label" for="event-date-select">Seleccioná fecha</label>
|
|
||||||
<select id="event-date-select" class="event-detail__date-select" [value]="selectedDateId()" (change)="selectDate($event)">
|
|
||||||
@for (date of item.dates; track date.id) {
|
|
||||||
<option [value]="date.id">{{ formatDate(date.date) }} · {{ date.time_start.slice(0, 5) }} h</option>
|
|
||||||
}
|
|
||||||
</select>
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (item.catalog_items?.length) {
|
|
||||||
<div class="event-detail__product-list">
|
|
||||||
@for (product of item.catalog_items; track product.id) {
|
|
||||||
<div class="event-detail__product row align-items-center gx-3 gy-2">
|
|
||||||
<h3 class="col-12 col-sm">{{ product.name }}</h3>
|
|
||||||
<div class="event-detail__product-action col-auto ms-auto ms-sm-0">
|
|
||||||
@if (needsSelection(product)) {
|
|
||||||
<a [routerLink]="['/producto', product.id]">Elegir opciones</a>
|
|
||||||
} @else {
|
|
||||||
<app-quantity-selector
|
|
||||||
[quantity]="quantityFor(product.id)"
|
|
||||||
[min]="0"
|
|
||||||
[max]="maximumQuantityFor(product)"
|
|
||||||
size="medium"
|
|
||||||
(decrease)="changeQuantity(product, -1)"
|
|
||||||
(increase)="changeQuantity(product, 1)"
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
<strong class="event-detail__price col-auto">{{ priceFor(product) }}</strong>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
<div class="event-detail__total"><span>Total</span><strong>{{ formatPrice(total()) }}</strong></div>
|
|
||||||
<div class="event-detail__buttons">
|
|
||||||
<app-button variant="cancel" (click)="cancel()">Cancelar</app-button>
|
|
||||||
<app-button variant="primary" [disabled]="total() === 0 || submitting()" (click)="buyNow()">
|
|
||||||
{{ submitting() ? 'Procesando…' : 'Comprar' }}
|
|
||||||
</app-button>
|
|
||||||
</div>
|
|
||||||
} @else {
|
|
||||||
<p class="event-detail__empty">Por ahora no hay productos disponibles para este evento.</p>
|
|
||||||
}
|
|
||||||
</section>
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
} @else if (!loading()) {
|
|
||||||
<p role="alert">No encontramos este evento.</p>
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
:host { display: block; color: #666666; }
|
|
||||||
.event-detail { margin-bottom: 3rem; }
|
|
||||||
.event-detail__sidebar, .event-detail__main { min-width: 0; }
|
|
||||||
.event-detail__image { background: #e7e8e9; }
|
|
||||||
.event-detail__image--placeholder { aspect-ratio: 1.43; display: grid; place-items: center; }
|
|
||||||
.event-detail__image img { width: 100%; height: auto; display: block; }
|
|
||||||
.event-detail__image span { font-size: 3rem; color: #aaa; }
|
|
||||||
.event-detail__description { margin-top: 1.5rem; }
|
|
||||||
.event-detail__description h2, .event-detail__social h2, .event-detail__section-heading h2 { margin: 0 0 .65rem; color: #666666; font-size: 15px; font-weight: 700; text-transform: uppercase; letter-spacing: .015em; }
|
|
||||||
.event-detail__description p { margin: 0; white-space: pre-line; line-height: 1.36; font-size: 14px; }
|
|
||||||
.event-detail__social { display: grid; gap: .35rem; margin-top: 2.3rem; }
|
|
||||||
.event-detail__social a { color: #666666; font-family: 'Gotham Book', sans-serif; font-size: 14px; font-weight: 400; display: flex; align-items: center; gap: .5rem; text-decoration: none; font-style: italic; }
|
|
||||||
.event-detail__social a:hover { color: var(--tenant-primary); text-decoration: underline; }
|
|
||||||
.event-detail__social i { width: 14px; font-size: 14px; text-align: center; }
|
|
||||||
.event-detail__map { margin-top: 16px; --location-map-min-height: 180px; --location-map-border-radius: 0; }
|
|
||||||
.event-detail__header { margin-bottom: 2rem; padding-top: .7rem; }
|
|
||||||
.event-detail__header h1 { margin: 0; color: #666666; font-size: 24px; line-height: 1.25; font-weight: 700; text-transform: uppercase; letter-spacing: .03em; }
|
|
||||||
.event-detail__subtitle { margin: .15rem 0 1.2rem; color: #666666; font-size: 18px; font-weight: 400; }
|
|
||||||
.event-detail__meta { display: grid; gap: .3rem; }
|
|
||||||
.event-detail__meta p { margin: 0; display: flex; align-items: baseline; gap: .4rem; color: #666666; font-family: 'Gotham Book', sans-serif; font-size: 12px; font-weight: 400; font-style: italic; }
|
|
||||||
.event-detail__meta i { width: .65rem; flex: none; text-align: center; }
|
|
||||||
.event-detail__section-heading { border-bottom: 1px solid #e2e4e6; margin-bottom: .9rem; }
|
|
||||||
.event-detail__section-heading h2 { margin-bottom: .5rem; }
|
|
||||||
.event-detail__date-label { display: block; margin-bottom: .4rem; color: #6b7175; font-size: .75rem; }
|
|
||||||
.event-detail__date-select { width: min(100%, 320px); padding: .55rem .75rem; border: 1px solid #d7d9db; border-radius: 4px; background: #fff; color: #555b60; font-size: .82rem; }
|
|
||||||
.event-detail__product-list { display: grid; gap: 28px; margin-top: 1.1rem; }
|
|
||||||
.event-detail__product { min-height: 40px; }
|
|
||||||
.event-detail__product h3 { min-width: 0; margin: 0; color: #838383; font-size: 20px; line-height: 1.2; font-weight: 700; text-transform: uppercase; }
|
|
||||||
.event-detail__product-action { width: 110px; text-align: right; }
|
|
||||||
.event-detail__product-action > a { color: var(--tenant-primary); font-size: .62rem; white-space: nowrap; }
|
|
||||||
.event-detail__price { width: 120px; color: #838383; font-size: 22px; font-weight: 900; text-align: right; white-space: nowrap; }
|
|
||||||
.event-detail__total { display: flex; justify-content: space-between; align-items: baseline; gap: 1rem; padding: .75rem 0 0; border-top: 1px solid #dfe2e4; margin-top: 1.15rem; font-size: 13px; color: #999999; text-transform: uppercase; }
|
|
||||||
.event-detail__total strong { color: var(--tenant-primary); font-size: 22px; font-weight: 900; }
|
|
||||||
.event-detail__buttons { display: flex; justify-content: flex-end; gap: .5rem; margin-top: 1.6rem; }
|
|
||||||
.event-detail__buttons app-button { min-width: 0; flex: 0 0 36%; }
|
|
||||||
.event-detail__empty { color: #7c8286; font-size: .85rem; }
|
|
||||||
@media (max-width: 575.98px) {
|
|
||||||
.event-detail__main { margin-top: 2rem; }
|
|
||||||
.event-detail__description, .event-detail__social { margin-top: 1.5rem; }
|
|
||||||
.event-detail__header { min-height: 0; margin-bottom: 2rem; }
|
|
||||||
.event-detail__buttons { flex-wrap: wrap; }
|
|
||||||
.event-detail__buttons app-button { flex: 1 1 100%; }
|
|
||||||
}
|
|
||||||
@@ -1,193 +0,0 @@
|
|||||||
import { HttpErrorResponse } from '@angular/common/http';
|
|
||||||
import { ChangeDetectionStrategy, Component, DestroyRef, computed, inject, signal } from '@angular/core';
|
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|
||||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
|
||||||
import { catchError, map, of, switchMap } from 'rxjs';
|
|
||||||
|
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
|
||||||
import { CheckoutService, DirectCheckoutItem } from '../../../../core/services/checkout.service';
|
|
||||||
import { StoreEvent } from '../../../../core/services/event/event.interface';
|
|
||||||
import { EventService } from '../../../../core/services/event/event.service';
|
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
|
||||||
import { ToastService } from '../../../../core/services/toast.service';
|
|
||||||
import { CounterToComponent } from '../../../../shared/components/counter-to/counter-to.component';
|
|
||||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
|
||||||
import { LocationMapComponent, MapLocation } from '../../../../shared/components/location-map/location-map.component';
|
|
||||||
import { QuantitySelectorComponent } from '../../../../shared/components/quantity-selector/quantity-selector.component';
|
|
||||||
|
|
||||||
type EventProduct = NonNullable<StoreEvent['catalog_items']>[number];
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'app-event-detail-page',
|
|
||||||
imports: [RouterLink, ButtonComponent, CounterToComponent, LocationMapComponent, QuantitySelectorComponent],
|
|
||||||
templateUrl: './event-detail-page.component.html',
|
|
||||||
styleUrl: './event-detail-page.component.scss',
|
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
||||||
})
|
|
||||||
export class EventDetailPageComponent {
|
|
||||||
private readonly route = inject(ActivatedRoute);
|
|
||||||
private readonly router = inject(Router);
|
|
||||||
private readonly events = inject(EventService);
|
|
||||||
private readonly checkout = inject(CheckoutService);
|
|
||||||
private readonly auth = inject(AuthService);
|
|
||||||
private readonly tenant = inject(TenantService);
|
|
||||||
private readonly toast = inject(ToastService);
|
|
||||||
private readonly destroyRef = inject(DestroyRef);
|
|
||||||
|
|
||||||
protected readonly event = signal<StoreEvent | null>(null);
|
|
||||||
protected readonly loading = signal(true);
|
|
||||||
protected readonly selectedDateId = signal<number | null>(null);
|
|
||||||
protected readonly quantities = signal<Record<number, number>>({});
|
|
||||||
protected readonly submitting = signal(false);
|
|
||||||
protected readonly mapLocations = computed<MapLocation[]>(() => {
|
|
||||||
const event = this.event();
|
|
||||||
const coordinates = event?.exact_location;
|
|
||||||
if (!event || !coordinates) return [];
|
|
||||||
|
|
||||||
return [{
|
|
||||||
id: event.id,
|
|
||||||
label: event.title,
|
|
||||||
latitude: coordinates.latitude,
|
|
||||||
longitude: coordinates.longitude,
|
|
||||||
address: event.location ?? undefined,
|
|
||||||
}];
|
|
||||||
});
|
|
||||||
protected readonly total = computed(() => (this.event()?.catalog_items ?? []).reduce((sum, product) => {
|
|
||||||
const choice = this.resolveChoice(product);
|
|
||||||
return sum + (choice ? choice.price * this.quantityFor(product.id) : 0);
|
|
||||||
}, 0));
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
this.route.paramMap.pipe(
|
|
||||||
map((params) => Number(params.get('id'))),
|
|
||||||
switchMap((id) => Number.isInteger(id) && id > 0
|
|
||||||
? this.events.get(id).pipe(map((response) => response.data), catchError(() => of(null)))
|
|
||||||
: of(null)),
|
|
||||||
takeUntilDestroyed(this.destroyRef),
|
|
||||||
).subscribe((event) => {
|
|
||||||
this.event.set(event);
|
|
||||||
this.selectedDateId.set(event?.dates?.[0]?.id ?? null);
|
|
||||||
this.quantities.set({});
|
|
||||||
this.loading.set(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
protected selectDate(event: Event): void {
|
|
||||||
const value = Number((event.target as HTMLSelectElement).value);
|
|
||||||
this.selectedDateId.set(Number.isInteger(value) ? value : null);
|
|
||||||
this.quantities.set({});
|
|
||||||
}
|
|
||||||
|
|
||||||
protected quantityFor(productId: number): number {
|
|
||||||
return this.quantities()[productId] ?? 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected changeQuantity(product: EventProduct, amount: number): void {
|
|
||||||
const choice = this.resolveChoice(product);
|
|
||||||
if (!choice) return;
|
|
||||||
const maximum = choice.maximumQuantity ?? Number.MAX_SAFE_INTEGER;
|
|
||||||
const quantity = Math.min(maximum, Math.max(0, this.quantityFor(product.id) + amount));
|
|
||||||
this.quantities.update((current) => ({ ...current, [product.id]: quantity }));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected maximumQuantityFor(product: EventProduct): number | null {
|
|
||||||
return this.resolveChoice(product)?.maximumQuantity ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected needsSelection(product: EventProduct): boolean {
|
|
||||||
return this.resolveChoice(product) === null;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected priceFor(product: EventProduct): string {
|
|
||||||
return this.formatPrice(this.resolveChoice(product)?.price ?? Number(product.price));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected formatPrice(price: number): string {
|
|
||||||
return '$' + price.toLocaleString('es-AR', { maximumFractionDigits: 0 });
|
|
||||||
}
|
|
||||||
|
|
||||||
protected formatDate(date: string): string {
|
|
||||||
const [year, month, day] = date.split('-').map(Number);
|
|
||||||
if (!year || !month || !day) return date;
|
|
||||||
return new Intl.DateTimeFormat('es-AR', { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' })
|
|
||||||
.format(new Date(Date.UTC(year, month - 1, day)));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected socialLabel(code: string): string {
|
|
||||||
const labels: Record<string, string> = {
|
|
||||||
instagram: 'Instagram', facebook: 'Facebook', whatsapp: 'WhatsApp',
|
|
||||||
youtube: 'YouTube', tiktok: 'TikTok', x: 'X', twitter: 'X',
|
|
||||||
};
|
|
||||||
return labels[code.toLowerCase()] ?? code;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected socialIcon(code: string): string {
|
|
||||||
const brands = ['instagram', 'facebook', 'whatsapp', 'youtube', 'tiktok', 'x-twitter', 'linkedin'];
|
|
||||||
const normalized = code.toLowerCase() === 'twitter' || code.toLowerCase() === 'x'
|
|
||||||
? 'x-twitter'
|
|
||||||
: code.toLowerCase();
|
|
||||||
return brands.includes(normalized) ? `fa-brands fa-${normalized}` : 'fa-solid fa-link';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected cancel(): void {
|
|
||||||
void this.router.navigate(['/']);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected async buyNow(): Promise<void> {
|
|
||||||
const event = this.event();
|
|
||||||
if (!event || this.submitting()) return;
|
|
||||||
|
|
||||||
const items: DirectCheckoutItem[] = [];
|
|
||||||
for (const product of event.catalog_items ?? []) {
|
|
||||||
const quantity = this.quantityFor(product.id);
|
|
||||||
if (quantity === 0) continue;
|
|
||||||
const choice = this.resolveChoice(product);
|
|
||||||
if (!choice) return;
|
|
||||||
items.push({ catalog_item_id: product.id, variant_id: choice.variantId, cantidad: quantity });
|
|
||||||
}
|
|
||||||
if (items.length === 0) return;
|
|
||||||
|
|
||||||
if (!this.auth.user()) {
|
|
||||||
await this.router.navigate(['/login'], { queryParams: { returnUrl: this.router.url } });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const tenant = this.tenant.tenant();
|
|
||||||
if (!tenant) {
|
|
||||||
this.toast.danger('No se pudo identificar la tienda.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.submitting.set(true);
|
|
||||||
try {
|
|
||||||
const purchase = await this.checkout.startCheckout(tenant.codigo, { direct_items: items });
|
|
||||||
await this.router.navigate(['/checkout', purchase.id]);
|
|
||||||
} catch (error) {
|
|
||||||
const message = error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
|
||||||
? error.error.message
|
|
||||||
: 'No se pudo iniciar la compra.';
|
|
||||||
this.toast.danger(message);
|
|
||||||
} finally {
|
|
||||||
this.submitting.set(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private resolveChoice(product: EventProduct): { variantId: number | null; price: number; maximumQuantity: number | null } | null {
|
|
||||||
if (product.requires_selection) return null;
|
|
||||||
if (product.variants.length === 0) {
|
|
||||||
return { variantId: null, price: Number(product.price), maximumQuantity: product.maximum_quantity };
|
|
||||||
}
|
|
||||||
|
|
||||||
const dateId = this.selectedDateId();
|
|
||||||
const candidates = product.variants.filter((variant) =>
|
|
||||||
dateId === null || variant.event_date_ids.length === 0 || variant.event_date_ids.includes(dateId));
|
|
||||||
if (candidates.length !== 1) return null;
|
|
||||||
|
|
||||||
return {
|
|
||||||
variantId: candidates[0].id,
|
|
||||||
price: Number(candidates[0].price),
|
|
||||||
maximumQuantity: candidates[0].maximum_quantity,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
import { ChangeDetectionStrategy, Component } from '@angular/core';
|
|
||||||
import { EventListComponent } from '../../components/event-list/event-list.component';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'app-event-home-page',
|
|
||||||
imports: [EventListComponent],
|
|
||||||
template: '<app-event-list />',
|
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
||||||
})
|
|
||||||
export class EventHomePageComponent {}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
import { ChangeDetectionStrategy, Component } from '@angular/core';
|
|
||||||
import { EventListComponent } from '../../components/event-list/event-list.component';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'app-event-search-page',
|
|
||||||
imports: [EventListComponent],
|
|
||||||
template: '<section aria-labelledby="event-search-title"><h1 id="event-search-title" class="h3 mb-4">Resultados de búsqueda</h1><app-event-list [search]="true" /></section>',
|
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
||||||
})
|
|
||||||
export class EventSearchPageComponent {}
|
|
||||||
@@ -3,21 +3,11 @@ import { provideRouter, Router } from '@angular/router';
|
|||||||
import { of, throwError } from 'rxjs';
|
import { of, throwError } from 'rxjs';
|
||||||
|
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
import { ToastService } from '../../../../core/services/toast.service';
|
|
||||||
import { LoginPageComponent } from './login-page.component';
|
import { LoginPageComponent } from './login-page.component';
|
||||||
|
|
||||||
describe('LoginPageComponent', () => {
|
describe('LoginPageComponent', () => {
|
||||||
let toastService: {
|
|
||||||
danger: ReturnType<typeof vi.fn>;
|
|
||||||
showAfterReload: ReturnType<typeof vi.fn>;
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
toastService = {
|
|
||||||
danger: vi.fn(),
|
|
||||||
showAfterReload: vi.fn(),
|
|
||||||
};
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('submits credentials and redirects to home with a full page reload on success', async () => {
|
it('submits credentials and redirects to home with a full page reload on success', async () => {
|
||||||
@@ -26,18 +16,14 @@ describe('LoginPageComponent', () => {
|
|||||||
of({
|
of({
|
||||||
id: 1,
|
id: 1,
|
||||||
nombre_apellido: 'Ada Lovelace',
|
nombre_apellido: 'Ada Lovelace',
|
||||||
email: 'ada@example.com',
|
email: 'ada@example.com'
|
||||||
}),
|
})
|
||||||
),
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [LoginPageComponent],
|
imports: [LoginPageComponent],
|
||||||
providers: [
|
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||||
provideRouter([]),
|
|
||||||
{ provide: AuthService, useValue: authService },
|
|
||||||
{ provide: ToastService, useValue: toastService },
|
|
||||||
],
|
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(LoginPageComponent);
|
const fixture = TestBed.createComponent(LoginPageComponent);
|
||||||
@@ -48,56 +34,17 @@ describe('LoginPageComponent', () => {
|
|||||||
|
|
||||||
component.form.setValue({
|
component.form.setValue({
|
||||||
email: 'ada@example.com',
|
email: 'ada@example.com',
|
||||||
password: 'secret123',
|
password: 'secret123'
|
||||||
});
|
});
|
||||||
|
|
||||||
component.onSubmit();
|
component.onSubmit();
|
||||||
|
|
||||||
expect(authService.login).toHaveBeenCalledWith({
|
expect(authService.login).toHaveBeenCalledWith({
|
||||||
email: 'ada@example.com',
|
email: 'ada@example.com',
|
||||||
password: 'secret123',
|
password: 'secret123'
|
||||||
});
|
});
|
||||||
expect(redirectSpy).toHaveBeenCalled();
|
expect(redirectSpy).toHaveBeenCalled();
|
||||||
expect(navigateSpy).not.toHaveBeenCalled();
|
expect(navigateSpy).not.toHaveBeenCalled();
|
||||||
expect(toastService.showAfterReload).toHaveBeenCalledWith(
|
|
||||||
'Sesión iniciada correctamente.',
|
|
||||||
'success',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('serializes a stored return URL before reloading so tenant base paths are restored', async () => {
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [LoginPageComponent],
|
|
||||||
providers: [
|
|
||||||
provideRouter([]),
|
|
||||||
{ provide: AuthService, useValue: {} },
|
|
||||||
{ provide: ToastService, useValue: toastService },
|
|
||||||
],
|
|
||||||
}).compileComponents();
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(LoginPageComponent);
|
|
||||||
const component = fixture.componentInstance as any;
|
|
||||||
const router = TestBed.inject(Router);
|
|
||||||
const assign = vi.fn();
|
|
||||||
const parsedUrl = router.parseUrl('/');
|
|
||||||
|
|
||||||
component.document = {
|
|
||||||
defaultView: {
|
|
||||||
sessionStorage: {
|
|
||||||
getItem: vi.fn().mockReturnValue('/'),
|
|
||||||
removeItem: vi.fn(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
location: { assign },
|
|
||||||
};
|
|
||||||
const parseUrlSpy = vi.spyOn(router, 'parseUrl').mockReturnValue(parsedUrl);
|
|
||||||
const serializeUrlSpy = vi.spyOn(router, 'serializeUrl').mockReturnValue('/sonder');
|
|
||||||
|
|
||||||
component.redirectToHome();
|
|
||||||
|
|
||||||
expect(parseUrlSpy).toHaveBeenCalledWith('/');
|
|
||||||
expect(serializeUrlSpy).toHaveBeenCalledWith(parsedUrl);
|
|
||||||
expect(assign).toHaveBeenCalledWith('/sonder');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('surfaces backend login errors', async () => {
|
it('surfaces backend login errors', async () => {
|
||||||
@@ -106,20 +53,16 @@ describe('LoginPageComponent', () => {
|
|||||||
throwError(() => ({
|
throwError(() => ({
|
||||||
error: {
|
error: {
|
||||||
errors: {
|
errors: {
|
||||||
email: ['Las credenciales son invalidas.'],
|
email: ['Las credenciales son invalidas.']
|
||||||
},
|
}
|
||||||
},
|
}
|
||||||
})),
|
}))
|
||||||
),
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [LoginPageComponent],
|
imports: [LoginPageComponent],
|
||||||
providers: [
|
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||||
provideRouter([]),
|
|
||||||
{ provide: AuthService, useValue: authService },
|
|
||||||
{ provide: ToastService, useValue: toastService },
|
|
||||||
],
|
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(LoginPageComponent);
|
const fixture = TestBed.createComponent(LoginPageComponent);
|
||||||
@@ -127,27 +70,22 @@ describe('LoginPageComponent', () => {
|
|||||||
|
|
||||||
component.form.setValue({
|
component.form.setValue({
|
||||||
email: 'ada@example.com',
|
email: 'ada@example.com',
|
||||||
password: 'wrong-password',
|
password: 'wrong-password'
|
||||||
});
|
});
|
||||||
|
|
||||||
component.onSubmit();
|
component.onSubmit();
|
||||||
|
|
||||||
expect(component.serverError()).toBe('Las credenciales son invalidas.');
|
expect(component.serverError()).toBe('Las credenciales son invalidas.');
|
||||||
expect(toastService.danger).toHaveBeenCalledWith('Las credenciales son invalidas.');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('validates email length and password minimum length before submit', async () => {
|
it('validates email length and password minimum length before submit', async () => {
|
||||||
const authService = {
|
const authService = {
|
||||||
login: vi.fn(),
|
login: vi.fn()
|
||||||
};
|
};
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [LoginPageComponent],
|
imports: [LoginPageComponent],
|
||||||
providers: [
|
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||||
provideRouter([]),
|
|
||||||
{ provide: AuthService, useValue: authService },
|
|
||||||
{ provide: ToastService, useValue: toastService },
|
|
||||||
],
|
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(LoginPageComponent);
|
const fixture = TestBed.createComponent(LoginPageComponent);
|
||||||
@@ -155,15 +93,12 @@ describe('LoginPageComponent', () => {
|
|||||||
|
|
||||||
component.form.setValue({
|
component.form.setValue({
|
||||||
email: `${'a'.repeat(250)}@example.com`,
|
email: `${'a'.repeat(250)}@example.com`,
|
||||||
password: '1234567',
|
password: '1234567'
|
||||||
});
|
});
|
||||||
component.onSubmit();
|
component.onSubmit();
|
||||||
|
|
||||||
expect(authService.login).not.toHaveBeenCalled();
|
expect(authService.login).not.toHaveBeenCalled();
|
||||||
expect(component.getControlError('email')).toBe('No puede superar los 255 caracteres.');
|
expect(component.getControlError('email')).toBe('No puede superar los 255 caracteres.');
|
||||||
expect(component.getControlError('password')).toBe('Debe tener al menos 8 caracteres.');
|
expect(component.getControlError('password')).toBe('Debe tener al menos 8 caracteres.');
|
||||||
expect(toastService.danger).toHaveBeenCalledWith(
|
|
||||||
'Revisá los datos ingresados para iniciar sesión.',
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
|
|||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
|
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
import { ToastService } from '../../../../core/services/toast.service';
|
|
||||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||||
import { InputComponent } from '../../../../shared/components/input/input.component';
|
import { InputComponent } from '../../../../shared/components/input/input.component';
|
||||||
|
|
||||||
@@ -17,14 +16,13 @@ const POST_LOGIN_RETURN_URL_KEY = 'shopit.auth.return-url';
|
|||||||
imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
|
imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
|
||||||
templateUrl: './login-page.component.html',
|
templateUrl: './login-page.component.html',
|
||||||
styleUrl: './login-page.component.scss',
|
styleUrl: './login-page.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
changeDetection: ChangeDetectionStrategy.OnPush
|
||||||
})
|
})
|
||||||
export class LoginPageComponent {
|
export class LoginPageComponent {
|
||||||
private readonly formBuilder = inject(FormBuilder);
|
private readonly formBuilder = inject(FormBuilder);
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
private readonly route = inject(ActivatedRoute);
|
private readonly route = inject(ActivatedRoute);
|
||||||
private readonly authService = inject(AuthService);
|
private readonly authService = inject(AuthService);
|
||||||
private readonly toastService = inject(ToastService);
|
|
||||||
private readonly document = inject(DOCUMENT);
|
private readonly document = inject(DOCUMENT);
|
||||||
private readonly platformId = inject(PLATFORM_ID);
|
private readonly platformId = inject(PLATFORM_ID);
|
||||||
|
|
||||||
@@ -34,7 +32,7 @@ export class LoginPageComponent {
|
|||||||
|
|
||||||
protected readonly form = this.formBuilder.nonNullable.group({
|
protected readonly form = this.formBuilder.nonNullable.group({
|
||||||
email: ['', [Validators.required, Validators.email, Validators.maxLength(EMAIL_MAX_LENGTH)]],
|
email: ['', [Validators.required, Validators.email, Validators.maxLength(EMAIL_MAX_LENGTH)]],
|
||||||
password: ['', [Validators.required, Validators.minLength(PASSWORD_MIN_LENGTH)]],
|
password: ['', [Validators.required, Validators.minLength(PASSWORD_MIN_LENGTH)]]
|
||||||
});
|
});
|
||||||
protected readonly submitted = this.submittedState.asReadonly();
|
protected readonly submitted = this.submittedState.asReadonly();
|
||||||
protected readonly serverError = this.serverErrorState.asReadonly();
|
protected readonly serverError = this.serverErrorState.asReadonly();
|
||||||
@@ -66,7 +64,6 @@ export class LoginPageComponent {
|
|||||||
|
|
||||||
if (this.form.invalid) {
|
if (this.form.invalid) {
|
||||||
this.form.markAllAsTouched();
|
this.form.markAllAsTouched();
|
||||||
this.toastService.danger('Revisá los datos ingresados para iniciar sesión.');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,13 +72,12 @@ export class LoginPageComponent {
|
|||||||
this.authService.login(this.form.getRawValue()).subscribe({
|
this.authService.login(this.form.getRawValue()).subscribe({
|
||||||
next: () => {
|
next: () => {
|
||||||
this.isSubmittingState.set(false);
|
this.isSubmittingState.set(false);
|
||||||
this.toastService.showAfterReload('Sesión iniciada correctamente.', 'success');
|
|
||||||
this.redirectToHome();
|
this.redirectToHome();
|
||||||
},
|
},
|
||||||
error: (error: unknown) => {
|
error: (error: unknown) => {
|
||||||
this.isSubmittingState.set(false);
|
this.isSubmittingState.set(false);
|
||||||
this.showLoginError(error);
|
this.serverErrorState.set(this.resolveErrorMessage(error));
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,7 +91,7 @@ export class LoginPageComponent {
|
|||||||
}
|
}
|
||||||
this.authService.loginWithGoogle();
|
this.authService.loginWithGoogle();
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
this.showLoginError(error);
|
this.serverErrorState.set(this.resolveErrorMessage(error));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,9 +139,10 @@ export class LoginPageComponent {
|
|||||||
const requestedUrl =
|
const requestedUrl =
|
||||||
this.route.snapshot.queryParamMap.get('returnUrl') ??
|
this.route.snapshot.queryParamMap.get('returnUrl') ??
|
||||||
this.document.defaultView?.sessionStorage.getItem(POST_LOGIN_RETURN_URL_KEY);
|
this.document.defaultView?.sessionStorage.getItem(POST_LOGIN_RETURN_URL_KEY);
|
||||||
const internalDestination =
|
const destination =
|
||||||
requestedUrl?.startsWith('/') && !requestedUrl.startsWith('//') ? requestedUrl : '/';
|
requestedUrl?.startsWith('/') && !requestedUrl.startsWith('//')
|
||||||
const destination = this.router.serializeUrl(this.router.parseUrl(internalDestination));
|
? requestedUrl
|
||||||
|
: this.router.serializeUrl(this.router.createUrlTree(['/']));
|
||||||
|
|
||||||
this.document.defaultView?.sessionStorage.removeItem(POST_LOGIN_RETURN_URL_KEY);
|
this.document.defaultView?.sessionStorage.removeItem(POST_LOGIN_RETURN_URL_KEY);
|
||||||
this.document.location.assign(destination);
|
this.document.location.assign(destination);
|
||||||
@@ -158,20 +155,13 @@ export class LoginPageComponent {
|
|||||||
this.authService.completeGoogleLogin(oauthCode).subscribe({
|
this.authService.completeGoogleLogin(oauthCode).subscribe({
|
||||||
next: () => {
|
next: () => {
|
||||||
this.isSubmittingState.set(false);
|
this.isSubmittingState.set(false);
|
||||||
this.toastService.showAfterReload('Sesión iniciada correctamente.', 'success');
|
|
||||||
this.redirectToHome();
|
this.redirectToHome();
|
||||||
},
|
},
|
||||||
error: (error: unknown) => {
|
error: (error: unknown) => {
|
||||||
this.isSubmittingState.set(false);
|
this.isSubmittingState.set(false);
|
||||||
this.showLoginError(error);
|
this.serverErrorState.set(this.resolveErrorMessage(error));
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
});
|
||||||
private showLoginError(error: unknown): void {
|
|
||||||
const message = this.resolveErrorMessage(error);
|
|
||||||
this.serverErrorState.set(message);
|
|
||||||
this.toastService.danger(message);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveErrorMessage(error: unknown): string {
|
private resolveErrorMessage(error: unknown): string {
|
||||||
|
|||||||
@@ -44,6 +44,7 @@
|
|||||||
[variants]="prod.variants"
|
[variants]="prod.variants"
|
||||||
[selectedVariant]="prod.selected_variant ?? null"
|
[selectedVariant]="prod.selected_variant ?? null"
|
||||||
[inventoryPolicy]="prod.inventory_policy"
|
[inventoryPolicy]="prod.inventory_policy"
|
||||||
|
[disabled]="!allows(prod.availability, 'select_variant')"
|
||||||
(variantChange)="onVariantChange($event)"
|
(variantChange)="onVariantChange($event)"
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
@@ -53,14 +54,22 @@
|
|||||||
|
|
||||||
<section class="product-detail__section">
|
<section class="product-detail__section">
|
||||||
<div class="product-detail__purchase">
|
<div class="product-detail__purchase">
|
||||||
<app-quantity-selector [(quantity)]="quantity" [max]="selectedVariantMax()" />
|
@if (restrictionMessage(); as message) {
|
||||||
|
<p class="mb-0 text-danger" role="status">{{ message }}</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<app-quantity-selector
|
||||||
|
[(quantity)]="quantity"
|
||||||
|
[max]="selectedVariantMax()"
|
||||||
|
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
|
||||||
|
/>
|
||||||
|
|
||||||
<div class="product-detail__actions">
|
<div class="product-detail__actions">
|
||||||
<app-button
|
<app-button
|
||||||
class="product-detail__cta"
|
class="product-detail__cta"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
type="button"
|
type="button"
|
||||||
[disabled]="!selectedVariantAvailable() || variantLoading() || addingToCart()"
|
[disabled]="!canAddToCart() || variantLoading() || addingToCart()"
|
||||||
(click)="addToCart()"
|
(click)="addToCart()"
|
||||||
>
|
>
|
||||||
@if (addingToCart()) {
|
@if (addingToCart()) {
|
||||||
@@ -75,9 +84,7 @@
|
|||||||
<app-button
|
<app-button
|
||||||
class="product-detail__cta"
|
class="product-detail__cta"
|
||||||
type="button"
|
type="button"
|
||||||
[disabled]="
|
[disabled]="!canBuyNow() || variantLoading() || creatingDirectPurchase()"
|
||||||
!selectedVariantAvailable() || variantLoading() || creatingDirectPurchase()
|
|
||||||
"
|
|
||||||
(click)="buyNow()"
|
(click)="buyNow()"
|
||||||
>
|
>
|
||||||
@if (variantLoading() || creatingDirectPurchase()) {
|
@if (variantLoading() || creatingDirectPurchase()) {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
|||||||
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
|
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
|
||||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
||||||
|
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import { ProductDetailPageComponent } from './product-detail-page.component';
|
import { ProductDetailPageComponent } from './product-detail-page.component';
|
||||||
@@ -38,7 +39,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,
|
||||||
maximum_addable_quantity: 10,
|
availability: createCatalogAvailability(10),
|
||||||
attributes: [],
|
attributes: [],
|
||||||
variants: [],
|
variants: [],
|
||||||
};
|
};
|
||||||
@@ -179,7 +180,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
|
|
||||||
it('reloads product availability when the cart changes', async () => {
|
it('reloads product availability when the cart changes', async () => {
|
||||||
catalogServiceStub.getCatalogItem.mockReturnValue(
|
catalogServiceStub.getCatalogItem.mockReturnValue(
|
||||||
of({ ...mockProduct, maximum_addable_quantity: 4 }),
|
of({ ...mockProduct, availability: createCatalogAvailability(4) }),
|
||||||
);
|
);
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
@@ -192,6 +193,21 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
expect(fixture.componentInstance['selectedVariantMax']()).toBe(4);
|
expect(fixture.componentInstance['selectedVariantMax']()).toBe(4);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('stops presenting a product that becomes hidden during an availability refresh', async () => {
|
||||||
|
catalogServiceStub.getCatalogItem.mockReturnValue(
|
||||||
|
throwError(() => new HttpErrorResponse({ status: 404 })),
|
||||||
|
);
|
||||||
|
await configureTestingModule();
|
||||||
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance['product']()).toBeNull();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('Este producto ya no está disponible.');
|
||||||
|
});
|
||||||
|
|
||||||
it('shows error message if the resolver cannot load the product', async () => {
|
it('shows error message if the resolver cannot load the product', async () => {
|
||||||
resolveProductError(PRODUCT_DETAIL_ERROR_MESSAGE);
|
resolveProductError(PRODUCT_DETAIL_ERROR_MESSAGE);
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
@@ -207,10 +223,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, maximum_addable_quantity: 10, values: {} }],
|
variants: [{ id: 123, availability: createCatalogAvailability(10), values: {} }],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 10,
|
availability: createCatalogAvailability(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: {},
|
||||||
},
|
},
|
||||||
@@ -312,11 +328,15 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
variants: [
|
variants: [
|
||||||
{ id: 123, maximum_addable_quantity: 10, values: { color: 'beige', material: 'Cuero' } },
|
{
|
||||||
|
id: 123,
|
||||||
|
availability: createCatalogAvailability(10),
|
||||||
|
values: { color: 'beige', material: 'Cuero' },
|
||||||
|
},
|
||||||
],
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 10,
|
availability: createCatalogAvailability(10),
|
||||||
images: ['https://example.com/variant1.png'],
|
images: ['https://example.com/variant1.png'],
|
||||||
values: {
|
values: {
|
||||||
color: 'beige',
|
color: 'beige',
|
||||||
@@ -353,8 +373,18 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
purpose: 'entry',
|
purpose: 'entry',
|
||||||
has_tickets: true,
|
has_tickets: true,
|
||||||
variants: [
|
variants: [
|
||||||
{ id: 101, event_date_id: 20, maximum_addable_quantity: 10, values: { event_date: '20' } },
|
{
|
||||||
{ id: 102, event_date_id: 21, maximum_addable_quantity: 10, values: { event_date: '21' } },
|
id: 101,
|
||||||
|
event_date_id: 20,
|
||||||
|
availability: createCatalogAvailability(10),
|
||||||
|
values: { event_date: '20' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 102,
|
||||||
|
event_date_id: 21,
|
||||||
|
availability: createCatalogAvailability(10),
|
||||||
|
values: { event_date: '21' },
|
||||||
|
},
|
||||||
],
|
],
|
||||||
attributes: [
|
attributes: [
|
||||||
{
|
{
|
||||||
@@ -385,7 +415,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 101,
|
id: 101,
|
||||||
event_date_id: 20,
|
event_date_id: 20,
|
||||||
maximum_addable_quantity: 10,
|
availability: createCatalogAvailability(10),
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -407,6 +437,8 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
|
|
||||||
options[1].click();
|
options[1].click();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
await fixture.whenStable();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, 102);
|
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, 102);
|
||||||
});
|
});
|
||||||
@@ -429,7 +461,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
|
|
||||||
fixture.componentInstance['selectedVariant'].set({
|
fixture.componentInstance['selectedVariant'].set({
|
||||||
id: 1,
|
id: 1,
|
||||||
maximum_addable_quantity: 10,
|
availability: createCatalogAvailability(10),
|
||||||
values: {},
|
values: {},
|
||||||
});
|
});
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -507,7 +539,9 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout', 44]);
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout'], {
|
||||||
|
queryParams: { purchase: 44 },
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the backend purchase-limit message for a direct checkout', async () => {
|
it('shows the backend purchase-limit message for a direct checkout', async () => {
|
||||||
@@ -517,7 +551,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
error: {
|
error: {
|
||||||
code: 'purchase.limit_exceeded',
|
code: 'purchase.limit_exceeded',
|
||||||
message: 'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
|
message: 'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
|
||||||
maximum_addable_quantity: 2,
|
availability: createCatalogAvailability(2),
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -542,13 +576,13 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
variants: [
|
variants: [
|
||||||
{
|
{
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 5,
|
availability: createCatalogAvailability(5),
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 5,
|
availability: createCatalogAvailability(5),
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -581,7 +615,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
resolveProduct({
|
resolveProduct({
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
variants: [],
|
variants: [],
|
||||||
maximum_addable_quantity: 4,
|
availability: createCatalogAvailability(4),
|
||||||
});
|
});
|
||||||
|
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
@@ -607,13 +641,13 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
variants: [
|
variants: [
|
||||||
{
|
{
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 5,
|
availability: createCatalogAvailability(5),
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 5,
|
availability: createCatalogAvailability(5),
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -645,7 +679,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,
|
||||||
maximum_addable_quantity: null,
|
availability: createCatalogAvailability(null),
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
@@ -653,7 +687,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
inventory_policy: 'unlimited',
|
inventory_policy: 'unlimited',
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 321,
|
id: 321,
|
||||||
maximum_addable_quantity: null,
|
availability: createCatalogAvailability(null),
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -677,7 +711,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,
|
||||||
maximum_addable_quantity: 2,
|
availability: createCatalogAvailability(2),
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
@@ -686,7 +720,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
max_units_per_user: 2,
|
max_units_per_user: 2,
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 322,
|
id: 322,
|
||||||
maximum_addable_quantity: 2,
|
availability: createCatalogAvailability(2),
|
||||||
images: [],
|
images: [],
|
||||||
values: { event_date: '20' },
|
values: { event_date: '20' },
|
||||||
},
|
},
|
||||||
@@ -710,14 +744,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,
|
||||||
maximum_addable_quantity: 0,
|
availability: createCatalogAvailability(0),
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 654,
|
id: 654,
|
||||||
maximum_addable_quantity: 0,
|
availability: createCatalogAvailability(0),
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -32,6 +32,13 @@ import { ProductDetailResolvedData } from './product-detail-page.resolver';
|
|||||||
import { CheckoutService } from '../../../../core/services/checkout.service';
|
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
|
import {
|
||||||
|
AVAILABLE_CATALOG_AVAILABILITY,
|
||||||
|
allowsCatalogAction,
|
||||||
|
combineCatalogAvailability,
|
||||||
|
maximumCatalogQuantity,
|
||||||
|
primaryAvailabilityMessage,
|
||||||
|
} from '../../../../core/services/catalog/catalog-availability';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-detail-page',
|
selector: 'app-product-detail-page',
|
||||||
@@ -96,29 +103,41 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
() => this.selectedVariant()?.precio ?? this.product()?.precio,
|
() => this.selectedVariant()?.precio ?? this.product()?.precio,
|
||||||
);
|
);
|
||||||
protected readonly quantity = signal(1);
|
protected readonly quantity = signal(1);
|
||||||
|
protected readonly effectiveAvailability = computed(() => {
|
||||||
|
const prod = this.product();
|
||||||
|
const variant = this.selectedVariant();
|
||||||
|
if (!prod) return AVAILABLE_CATALOG_AVAILABILITY;
|
||||||
|
|
||||||
|
return combineCatalogAvailability(prod.availability, variant?.availability);
|
||||||
|
});
|
||||||
protected readonly selectedVariantMax = computed<number | null>(() => {
|
protected readonly selectedVariantMax = computed<number | null>(() => {
|
||||||
const prod = this.product();
|
const prod = this.product();
|
||||||
const variant = this.selectedVariant();
|
const variant = this.selectedVariant();
|
||||||
if (!prod) return 0;
|
if (!prod) return 0;
|
||||||
|
if (!variant && prod.variants.length > 0) return 0;
|
||||||
|
|
||||||
return variant
|
return maximumCatalogQuantity(this.effectiveAvailability());
|
||||||
? (variant.maximum_addable_quantity ?? null)
|
|
||||||
: prod.variants.length === 0
|
|
||||||
? (prod.maximum_addable_quantity ?? null)
|
|
||||||
: 0;
|
|
||||||
});
|
});
|
||||||
protected readonly selectedVariantAvailable = computed(() => {
|
protected readonly hasPurchasableSelection = 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();
|
return prod.variants.length === 0 || this.selectedVariant() !== null;
|
||||||
if (variant) return this.isVariantAvailable(variant);
|
|
||||||
if (prod.purpose === 'entry') return false;
|
|
||||||
if (prod.variants.length > 0) return false;
|
|
||||||
|
|
||||||
return this.selectedVariantMax() !== 0;
|
|
||||||
});
|
});
|
||||||
|
protected readonly canAddToCart = computed(
|
||||||
|
() =>
|
||||||
|
this.hasPurchasableSelection() &&
|
||||||
|
allowsCatalogAction(this.effectiveAvailability(), 'add_to_cart'),
|
||||||
|
);
|
||||||
|
protected readonly canBuyNow = computed(
|
||||||
|
() =>
|
||||||
|
this.hasPurchasableSelection() &&
|
||||||
|
allowsCatalogAction(this.effectiveAvailability(), 'buy_now'),
|
||||||
|
);
|
||||||
|
protected readonly restrictionMessage = computed(() =>
|
||||||
|
primaryAvailabilityMessage(this.effectiveAvailability()),
|
||||||
|
);
|
||||||
|
protected readonly allows = allowsCatalogAction;
|
||||||
protected readonly descriptionExpanded = signal(false);
|
protected readonly descriptionExpanded = signal(false);
|
||||||
protected readonly descriptionMaxHeight = signal(0);
|
protected readonly descriptionMaxHeight = signal(0);
|
||||||
protected readonly descriptionHasOverflow = signal(false);
|
protected readonly descriptionHasOverflow = signal(false);
|
||||||
@@ -224,8 +243,12 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
this.quantity.set(Math.max(1, maximum));
|
this.quantity.set(Math.max(1, maximum));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error: () => {
|
error: (error: HttpErrorResponse) => {
|
||||||
// Keep the last known availability if the silent refresh fails.
|
if (error.status === 404) {
|
||||||
|
this.product.set(null);
|
||||||
|
this.selectedVariant.set(null);
|
||||||
|
this.error.set('Este producto ya no está disponible.');
|
||||||
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -295,8 +318,10 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
protected addToCart(): void {
|
protected addToCart(): void {
|
||||||
const currentProduct = this.product();
|
const currentProduct = this.product();
|
||||||
const variant = this.selectedVariant();
|
const variant = this.selectedVariant();
|
||||||
if (!currentProduct || !this.selectedVariantAvailable()) {
|
if (!currentProduct || !this.canAddToCart()) {
|
||||||
this.toastService.danger('Por favor, selecciona una variante.');
|
this.toastService.danger(
|
||||||
|
this.effectiveAvailability().reasons[0]?.message ?? 'Por favor, selecciona una variante.',
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -326,8 +351,10 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!currentProduct || !this.selectedVariantAvailable()) {
|
if (!currentProduct || !this.canBuyNow()) {
|
||||||
this.toastService.danger('Por favor, selecciona una variante.');
|
this.toastService.danger(
|
||||||
|
this.effectiveAvailability().reasons[0]?.message ?? 'Por favor, selecciona una variante.',
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -358,7 +385,9 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.router.navigate(['/checkout', 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);
|
||||||
const message =
|
const message =
|
||||||
@@ -371,10 +400,6 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
|
||||||
return variant.maximum_addable_quantity !== 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected toggleDescription(): void {
|
protected toggleDescription(): void {
|
||||||
this.descriptionExpanded.update((current) => !current);
|
this.descriptionExpanded.update((current) => !current);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|||||||
|
|
||||||
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
|
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
|
||||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||||
|
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||||
import {
|
import {
|
||||||
PRODUCT_DETAIL_ERROR_MESSAGE,
|
PRODUCT_DETAIL_ERROR_MESSAGE,
|
||||||
PRODUCT_DETAIL_INVALID_ID_MESSAGE,
|
PRODUCT_DETAIL_INVALID_ID_MESSAGE,
|
||||||
@@ -29,7 +30,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,
|
||||||
maximum_addable_quantity: 0,
|
availability: createCatalogAvailability(0),
|
||||||
attributes: [],
|
attributes: [],
|
||||||
variants: [],
|
variants: [],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -17,9 +17,7 @@
|
|||||||
|
|
||||||
<div class="status-content__section status-content__section--secondary">
|
<div class="status-content__section status-content__section--secondary">
|
||||||
@if (ticketsRoute()) {
|
@if (ticketsRoute()) {
|
||||||
<p class="status-content__message">
|
<p class="status-content__message">A continuación, vas a poder ver los tickets que debés presentar en el evento.</p>
|
||||||
A continuación, vas a poder ver los tickets que debés presentar en el evento.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<app-button
|
<app-button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -31,9 +29,7 @@
|
|||||||
<span>Mis tickets</span>
|
<span>Mis tickets</span>
|
||||||
</app-button>
|
</app-button>
|
||||||
} @else if (whatsappUrl()) {
|
} @else if (whatsappUrl()) {
|
||||||
<p class="status-content__message">
|
<p class="status-content__message">Comunicate con nosotros para coordinar el envío.</p>
|
||||||
Comunicate con nosotros para coordinar el envío.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<app-button
|
<app-button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -55,21 +51,13 @@
|
|||||||
<i class="fa-solid fa-clock"></i>
|
<i class="fa-solid fa-clock"></i>
|
||||||
</div>
|
</div>
|
||||||
<h2 class="status-content__title">ESTAMOS VERIFICANDO TU PAGO</h2>
|
<h2 class="status-content__title">ESTAMOS VERIFICANDO TU PAGO</h2>
|
||||||
<p class="status-content__subtitle">
|
<p class="status-content__subtitle">Tu compra ya fue registrada y estamos esperando la confirmación del pago.</p>
|
||||||
Tu compra ya fue registrada y estamos esperando la confirmación del pago.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<hr class="status-content__divider" />
|
<hr class="status-content__divider" />
|
||||||
|
|
||||||
<div class="status-content__section status-content__section--secondary">
|
<div class="status-content__section status-content__section--secondary">
|
||||||
@if (paymentIssueMessage()) {
|
|
||||||
<p class="status-content__message">
|
|
||||||
{{ paymentIssueMessage() }} Estamos revisando el pago.
|
|
||||||
</p>
|
|
||||||
} @else {
|
|
||||||
<p class="status-content__message">Te avisaremos cuando el pago sea confirmado.</p>
|
<p class="status-content__message">Te avisaremos cuando el pago sea confirmado.</p>
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
} @else if (status() === 'expired') {
|
} @else if (status() === 'expired') {
|
||||||
<div class="status-content__section status-content__section--primary">
|
<div class="status-content__section status-content__section--primary">
|
||||||
@@ -77,17 +65,13 @@
|
|||||||
<i class="fa-solid fa-clock"></i>
|
<i class="fa-solid fa-clock"></i>
|
||||||
</div>
|
</div>
|
||||||
<h2 class="status-content__title">LA COMPRA VENCIÓ</h2>
|
<h2 class="status-content__title">LA COMPRA VENCIÓ</h2>
|
||||||
<p class="status-content__subtitle">
|
<p class="status-content__subtitle">El plazo de pago terminó y liberamos el stock reservado.</p>
|
||||||
El plazo de pago terminó y liberamos el stock reservado.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<hr class="status-content__divider" />
|
<hr class="status-content__divider" />
|
||||||
|
|
||||||
<div class="status-content__section status-content__section--secondary">
|
<div class="status-content__section status-content__section--secondary">
|
||||||
<p class="status-content__message">
|
<p class="status-content__message">Podés volver a la tienda e iniciar una nueva compra.</p>
|
||||||
Podés volver a la tienda e iniciar una nueva compra.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
} @else if (status() === 'rejected') {
|
} @else if (status() === 'rejected') {
|
||||||
<div class="status-content__section status-content__section--primary">
|
<div class="status-content__section status-content__section--primary">
|
||||||
@@ -95,9 +79,7 @@
|
|||||||
<i class="fa-solid fa-triangle-exclamation"></i>
|
<i class="fa-solid fa-triangle-exclamation"></i>
|
||||||
</div>
|
</div>
|
||||||
<h2 class="status-content__title">NO PUDIMOS CONFIRMAR EL PAGO</h2>
|
<h2 class="status-content__title">NO PUDIMOS CONFIRMAR EL PAGO</h2>
|
||||||
<p class="status-content__subtitle">
|
<p class="status-content__subtitle">Revisá el medio de pago o comunicate con nosotros para continuar.</p>
|
||||||
Revisá el medio de pago o comunicate con nosotros para continuar.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<hr class="status-content__divider" />
|
<hr class="status-content__divider" />
|
||||||
@@ -132,9 +114,7 @@
|
|||||||
<hr class="status-content__divider" />
|
<hr class="status-content__divider" />
|
||||||
|
|
||||||
<div class="status-content__section status-content__section--secondary">
|
<div class="status-content__section status-content__section--secondary">
|
||||||
<p class="status-content__message">
|
<p class="status-content__message">Volvé a ingresar más tarde. Si el problema sigue, comunicate con nosotros.</p>
|
||||||
Volvé a ingresar más tarde. Si el problema sigue, comunicate con nosotros.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
@if (whatsappUrl()) {
|
@if (whatsappUrl()) {
|
||||||
<div class="status-content__actions">
|
<div class="status-content__actions">
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import {
|
|||||||
CheckoutService,
|
CheckoutService,
|
||||||
PurchaseDetailResponse,
|
PurchaseDetailResponse,
|
||||||
} from '../../../../core/services/checkout.service';
|
} from '../../../../core/services/checkout.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.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';
|
||||||
@@ -67,13 +66,9 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function render(
|
async function render(hasGeneratedTickets: boolean) {
|
||||||
hasGeneratedTickets: boolean,
|
|
||||||
forcedStatus?: string,
|
|
||||||
purchaseResponse = purchase(hasGeneratedTickets),
|
|
||||||
) {
|
|
||||||
const checkoutService = {
|
const checkoutService = {
|
||||||
getPurchase: vi.fn().mockResolvedValue(purchaseResponse),
|
getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)),
|
||||||
withCustomLoading() {
|
withCustomLoading() {
|
||||||
return this;
|
return this;
|
||||||
},
|
},
|
||||||
@@ -82,22 +77,15 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
navigate: vi.fn().mockResolvedValue(true),
|
navigate: vi.fn().mockResolvedValue(true),
|
||||||
navigateByUrl: vi.fn().mockResolvedValue(true),
|
navigateByUrl: vi.fn().mockResolvedValue(true),
|
||||||
};
|
};
|
||||||
const cartService = { clearCart: vi.fn() };
|
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [PurchaseStatusPageComponent],
|
imports: [PurchaseStatusPageComponent],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: CheckoutService, useValue: checkoutService },
|
{ provide: CheckoutService, useValue: checkoutService },
|
||||||
{ provide: CartService, useValue: cartService },
|
|
||||||
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
useValue: {
|
useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } },
|
||||||
snapshot: {
|
|
||||||
paramMap: convertToParamMap({ id: '42' }),
|
|
||||||
queryParamMap: convertToParamMap(forcedStatus ? { status: forcedStatus } : {}),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{ provide: Router, useValue: router },
|
{ provide: Router, useValue: router },
|
||||||
],
|
],
|
||||||
@@ -112,22 +100,15 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
fixture,
|
fixture,
|
||||||
element: fixture.nativeElement as HTMLElement,
|
element: fixture.nativeElement as HTMLElement,
|
||||||
checkoutService,
|
checkoutService,
|
||||||
cartService,
|
|
||||||
router,
|
router,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
it('clears the cart when the purchase is approved', async () => {
|
|
||||||
const { cartService } = await render(true);
|
|
||||||
|
|
||||||
expect(cartService.clearCart).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows the tickets action when this purchase generated tickets', async () => {
|
it('shows the tickets action when this purchase generated tickets', async () => {
|
||||||
const { element, checkoutService, router } = await render(true);
|
const { element, checkoutService, router } = await render(true);
|
||||||
|
|
||||||
expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
|
expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
|
||||||
expect(element.textContent).toContain('Mis tickets');
|
expect(element.textContent).toContain('Ver mis tickets');
|
||||||
expect(element.textContent).not.toContain('WhatsApp');
|
expect(element.textContent).not.toContain('WhatsApp');
|
||||||
|
|
||||||
element.querySelector<HTMLButtonElement>('app-button button')?.click();
|
element.querySelector<HTMLButtonElement>('app-button button')?.click();
|
||||||
@@ -153,38 +134,6 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
openSpy.mockRestore();
|
openSpy.mockRestore();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the expired result without polling when checkout redirects after expiration', async () => {
|
|
||||||
const { element, checkoutService } = await render(false, 'expired');
|
|
||||||
|
|
||||||
expect(element.textContent).toContain('LA COMPRA VENCIÓ');
|
|
||||||
expect(element.textContent).not.toContain('ESTAMOS VERIFICANDO TU PAGO');
|
|
||||||
expect(checkoutService.getPurchase).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows the primary transfer candidate issue while the purchase is in review', async () => {
|
|
||||||
const { element } = await render(false, undefined, {
|
|
||||||
status: 'in_review',
|
|
||||||
payment_verification: {
|
|
||||||
status: 'candidate',
|
|
||||||
candidate_count: 2,
|
|
||||||
primary: {
|
|
||||||
reason: 'exact_dni_near_amount',
|
|
||||||
dni_distance: 0,
|
|
||||||
payment_amount: '49000.00',
|
|
||||||
purchase_amount: '50000.00',
|
|
||||||
amount_difference: '1000.00',
|
|
||||||
confidence: 'high',
|
|
||||||
detected_at: '2026-08-27T18:00:00-03:00',
|
|
||||||
},
|
|
||||||
reasons: ['exact_dni_near_amount', 'exact_amount_near_dni'],
|
|
||||||
},
|
|
||||||
} as PurchaseDetailResponse);
|
|
||||||
|
|
||||||
expect(element.textContent).toContain('Encontramos 2 transferencias posibles.');
|
|
||||||
expect(element.textContent).toMatch(/diferencia de \$\s*1\.000/);
|
|
||||||
expect(element.textContent).toContain('Estamos revisando el pago.');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('polls every five seconds while the payment is pending and shows the confirmation', async () => {
|
it('polls every five seconds while the payment is pending and shows the confirmation', async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
|
|
||||||
@@ -198,13 +147,11 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
return this;
|
return this;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
const cartService = { clearCart: vi.fn() };
|
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [PurchaseStatusPageComponent],
|
imports: [PurchaseStatusPageComponent],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: CheckoutService, useValue: checkoutService },
|
{ provide: CheckoutService, useValue: checkoutService },
|
||||||
{ provide: CartService, useValue: cartService },
|
|
||||||
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
@@ -227,7 +174,6 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
|
|
||||||
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
||||||
expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!');
|
expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!');
|
||||||
expect(cartService.clearCart).toHaveBeenCalledOnce();
|
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(10_000);
|
await vi.advanceTimersByTimeAsync(10_000);
|
||||||
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
||||||
@@ -251,7 +197,6 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
imports: [PurchaseStatusPageComponent],
|
imports: [PurchaseStatusPageComponent],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: CheckoutService, useValue: checkoutService },
|
{ provide: CheckoutService, useValue: checkoutService },
|
||||||
{ provide: CartService, useValue: { clearCart: vi.fn() } },
|
|
||||||
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
|
|||||||
@@ -13,10 +13,8 @@ import { ActivatedRoute, Router } from '@angular/router';
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
CheckoutService,
|
CheckoutService,
|
||||||
PurchasePaymentVerificationResponse,
|
|
||||||
PurchaseStatusResponse,
|
PurchaseStatusResponse,
|
||||||
} from '../../../../core/services/checkout.service';
|
} from '../../../../core/services/checkout.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.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';
|
||||||
@@ -37,7 +35,6 @@ 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 cartService = inject(CartService);
|
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
|
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
|
||||||
|
|
||||||
@@ -49,7 +46,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly isLoading = signal(true);
|
protected readonly isLoading = signal(true);
|
||||||
protected readonly status = signal<PurchaseStatusView>('pending');
|
protected readonly status = signal<PurchaseStatusView>('pending');
|
||||||
protected readonly hasGeneratedTickets = signal(false);
|
protected readonly hasGeneratedTickets = signal(false);
|
||||||
protected readonly paymentIssueMessage = signal<string | null>(null);
|
|
||||||
protected readonly ticketsRoute = computed(() => {
|
protected readonly ticketsRoute = computed(() => {
|
||||||
if (!this.hasGeneratedTickets()) {
|
if (!this.hasGeneratedTickets()) {
|
||||||
return null;
|
return null;
|
||||||
@@ -76,12 +72,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
this.purchaseId = purchaseId;
|
this.purchaseId = purchaseId;
|
||||||
this.tenantCode = tenant.codigo;
|
this.tenantCode = tenant.codigo;
|
||||||
|
|
||||||
if (this.route.snapshot.queryParamMap?.get('status') === 'expired') {
|
|
||||||
this.status.set('expired');
|
|
||||||
this.isLoading.set(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
void this.loadStatus();
|
void this.loadStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,11 +97,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
const status = this.resolveStatus(purchase);
|
const status = this.resolveStatus(purchase);
|
||||||
this.status.set(status);
|
this.status.set(status);
|
||||||
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
|
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
|
||||||
this.paymentIssueMessage.set(this.resolvePaymentIssueMessage(purchase.payment_verification));
|
|
||||||
|
|
||||||
if (status === 'approved') {
|
|
||||||
this.cartService.clearCart();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status === 'pending') {
|
if (status === 'pending') {
|
||||||
this.schedulePolling();
|
this.schedulePolling();
|
||||||
@@ -122,10 +107,7 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
console.error('Failed to fetch purchase status:', error);
|
console.error('Failed to fetch purchase status:', error);
|
||||||
|
|
||||||
if (!this.isDestroyed) {
|
if (!this.isDestroyed) {
|
||||||
if (this.isPurchaseExpiredError(error)) {
|
if (isPolling) {
|
||||||
this.status.set('expired');
|
|
||||||
this.stopPolling();
|
|
||||||
} else if (isPolling) {
|
|
||||||
this.schedulePolling();
|
this.schedulePolling();
|
||||||
} else {
|
} else {
|
||||||
this.status.set('error');
|
this.status.set('error');
|
||||||
@@ -172,51 +154,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
return 'pending';
|
return 'pending';
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolvePaymentIssueMessage(
|
|
||||||
verification?: PurchasePaymentVerificationResponse,
|
|
||||||
): string | null {
|
|
||||||
const primary = verification?.primary;
|
|
||||||
|
|
||||||
if (!primary) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const primaryMessage = (() => {
|
|
||||||
switch (primary.reason) {
|
|
||||||
case 'ambiguous_exact_match':
|
|
||||||
return 'Encontramos una transferencia que también coincide con otra compra.';
|
|
||||||
case 'exact_dni_near_amount':
|
|
||||||
return `El DNI coincide, pero el monto transferido tiene una diferencia de ${this.formatCurrency(primary.amount_difference)}.`;
|
|
||||||
case 'exact_amount_near_dni':
|
|
||||||
return primary.dni_distance === null
|
|
||||||
? 'El monto coincide, pero el DNI del pagador es diferente.'
|
|
||||||
: `El monto coincide, pero el DNI del pagador presenta ${primary.dni_distance} ${primary.dni_distance === 1 ? 'diferencia' : 'diferencias'} de escritura.`;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
if (verification.candidate_count > 1) {
|
|
||||||
return `Encontramos ${verification.candidate_count} transferencias posibles. ${primaryMessage}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return primaryMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
private formatCurrency(amount: string): string {
|
|
||||||
return new Intl.NumberFormat('es-AR', {
|
|
||||||
style: 'currency',
|
|
||||||
currency: 'ARS',
|
|
||||||
maximumFractionDigits: 2,
|
|
||||||
}).format(Number(amount));
|
|
||||||
}
|
|
||||||
|
|
||||||
private isPurchaseExpiredError(error: unknown): boolean {
|
|
||||||
if (typeof error !== 'object' || error === null || !('error' in error)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (error as { error?: { code?: string } }).error?.code === 'purchase.expired';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected goToTickets(): void {
|
protected goToTickets(): void {
|
||||||
const route = this.ticketsRoute();
|
const route = this.ticketsRoute();
|
||||||
|
|
||||||
|
|||||||
@@ -38,13 +38,11 @@
|
|||||||
<label class="visually-hidden" for="register-password">Contraseña</label>
|
<label class="visually-hidden" for="register-password">Contraseña</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="register-password"
|
id="register-password"
|
||||||
type="password-toggle"
|
type="password"
|
||||||
placeholder="Contraseña"
|
placeholder="Contraseña"
|
||||||
[value]="form.controls.password.value"
|
[value]="form.controls.password.value"
|
||||||
[invalid]="showControlError('password')"
|
[invalid]="showControlError('password')"
|
||||||
[visible]="passwordVisible()"
|
|
||||||
(valueChange)="updateField('password', $event)"
|
(valueChange)="updateField('password', $event)"
|
||||||
(visibleChange)="setPasswordVisibility($event)"
|
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password'); as errorMessage) {
|
@if (getControlError('password'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
@@ -53,13 +51,11 @@
|
|||||||
<label class="visually-hidden" for="register-password-repeat">Repetir Contraseña</label>
|
<label class="visually-hidden" for="register-password-repeat">Repetir Contraseña</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="register-password-repeat"
|
id="register-password-repeat"
|
||||||
type="password-toggle"
|
type="password"
|
||||||
placeholder="Repetir Contraseña"
|
placeholder="Repetir Contraseña"
|
||||||
[value]="form.controls.password_confirmation.value"
|
[value]="form.controls.password_confirmation.value"
|
||||||
[invalid]="showControlError('password_confirmation')"
|
[invalid]="showControlError('password_confirmation')"
|
||||||
[visible]="passwordVisible()"
|
|
||||||
(valueChange)="updateField('password_confirmation', $event)"
|
(valueChange)="updateField('password_confirmation', $event)"
|
||||||
(visibleChange)="setPasswordVisibility($event)"
|
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password_confirmation'); as errorMessage) {
|
@if (getControlError('password_confirmation'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
|||||||
@@ -12,48 +12,6 @@ describe('RegisterPageComponent', () => {
|
|||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows and hides both password fields with either visibility control', async () => {
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [RegisterPageComponent],
|
|
||||||
providers: [
|
|
||||||
provideRouter([]),
|
|
||||||
{ provide: AuthService, useValue: { register: vi.fn() } },
|
|
||||||
{ provide: ModalService, useValue: { openSimple: vi.fn() } },
|
|
||||||
{ provide: ToastService, useValue: { danger: vi.fn() } }
|
|
||||||
]
|
|
||||||
}).compileComponents();
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(RegisterPageComponent);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
const getPasswordInputs = () =>
|
|
||||||
Array.from(
|
|
||||||
fixture.nativeElement.querySelectorAll(
|
|
||||||
'input#register-password, input#register-password-repeat'
|
|
||||||
)
|
|
||||||
) as HTMLInputElement[];
|
|
||||||
const getVisibilityButtons = () =>
|
|
||||||
Array.from(
|
|
||||||
fixture.nativeElement.querySelectorAll('button[aria-label]')
|
|
||||||
) as HTMLButtonElement[];
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
|
||||||
|
|
||||||
getVisibilityButtons()[0].click();
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['text', 'text']);
|
|
||||||
expect(getVisibilityButtons().map((button) => button.getAttribute('aria-label'))).toEqual([
|
|
||||||
'Ocultar contraseña',
|
|
||||||
'Ocultar contraseña'
|
|
||||||
]);
|
|
||||||
|
|
||||||
getVisibilityButtons()[1].click();
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('submits registration data and redirects to /login on success', async () => {
|
it('submits registration data and redirects to /login on success', async () => {
|
||||||
const authService = {
|
const authService = {
|
||||||
register: vi.fn().mockReturnValue(
|
register: vi.fn().mockReturnValue(
|
||||||
@@ -105,7 +63,7 @@ describe('RegisterPageComponent', () => {
|
|||||||
password_confirmation: 'Secret!123'
|
password_confirmation: 'Secret!123'
|
||||||
});
|
});
|
||||||
expect(modalService.openSimple).toHaveBeenCalledWith({
|
expect(modalService.openSimple).toHaveBeenCalledWith({
|
||||||
title: 'Tu cuenta fue creada correctamente',
|
content: 'Tu cuenta fue creada correctamente',
|
||||||
buttonLabel: 'Cerrar'
|
buttonLabel: 'Cerrar'
|
||||||
});
|
});
|
||||||
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
||||||
|
|||||||
@@ -48,7 +48,6 @@ export class RegisterPageComponent {
|
|||||||
private readonly submittedState = signal(false);
|
private readonly submittedState = signal(false);
|
||||||
private readonly serverErrorState = signal<string | null>(null);
|
private readonly serverErrorState = signal<string | null>(null);
|
||||||
private readonly isSubmittingState = signal(false);
|
private readonly isSubmittingState = signal(false);
|
||||||
private readonly passwordVisibleState = signal(false);
|
|
||||||
|
|
||||||
protected readonly form = this.formBuilder.nonNullable.group({
|
protected readonly form = this.formBuilder.nonNullable.group({
|
||||||
nombre_apellido: ['', [Validators.required, Validators.maxLength(TEXT_MAX_LENGTH)]],
|
nombre_apellido: ['', [Validators.required, Validators.maxLength(TEXT_MAX_LENGTH)]],
|
||||||
@@ -68,11 +67,6 @@ export class RegisterPageComponent {
|
|||||||
protected readonly submitted = this.submittedState.asReadonly();
|
protected readonly submitted = this.submittedState.asReadonly();
|
||||||
protected readonly serverError = this.serverErrorState.asReadonly();
|
protected readonly serverError = this.serverErrorState.asReadonly();
|
||||||
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
||||||
protected readonly passwordVisible = this.passwordVisibleState.asReadonly();
|
|
||||||
|
|
||||||
protected setPasswordVisibility(visible: boolean): void {
|
|
||||||
this.passwordVisibleState.set(visible);
|
|
||||||
}
|
|
||||||
|
|
||||||
goToLogin(): void {
|
goToLogin(): void {
|
||||||
void this.router.navigate(['/login']);
|
void this.router.navigate(['/login']);
|
||||||
@@ -93,7 +87,7 @@ export class RegisterPageComponent {
|
|||||||
next: () => {
|
next: () => {
|
||||||
this.isSubmittingState.set(false);
|
this.isSubmittingState.set(false);
|
||||||
this.modalService.openSimple({
|
this.modalService.openSimple({
|
||||||
title: 'Tu cuenta fue creada correctamente',
|
content: 'Tu cuenta fue creada correctamente',
|
||||||
buttonLabel: 'Cerrar'
|
buttonLabel: 'Cerrar'
|
||||||
}).subscribe(() => {
|
}).subscribe(() => {
|
||||||
void this.router.navigate(['/login']);
|
void this.router.navigate(['/login']);
|
||||||
|
|||||||
@@ -13,13 +13,11 @@
|
|||||||
<label class="visually-hidden" for="reset-password-new">Nueva Contraseña</label>
|
<label class="visually-hidden" for="reset-password-new">Nueva Contraseña</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="reset-password-new"
|
id="reset-password-new"
|
||||||
type="password-toggle"
|
type="password"
|
||||||
placeholder="Nueva Contraseña"
|
placeholder="Nueva Contraseña"
|
||||||
[value]="form.controls.password.value"
|
[value]="form.controls.password.value"
|
||||||
[invalid]="showControlError('password')"
|
[invalid]="showControlError('password')"
|
||||||
[visible]="passwordVisible()"
|
|
||||||
(valueChange)="updatePassword('password', $event)"
|
(valueChange)="updatePassword('password', $event)"
|
||||||
(visibleChange)="setPasswordVisibility($event)"
|
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password'); as errorMessage) {
|
@if (getControlError('password'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
@@ -32,13 +30,11 @@
|
|||||||
</label>
|
</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="reset-password-confirmation"
|
id="reset-password-confirmation"
|
||||||
type="password-toggle"
|
type="password"
|
||||||
placeholder="Repetir Nueva Contraseña"
|
placeholder="Repetir Nueva Contraseña"
|
||||||
[value]="form.controls.password_confirmation.value"
|
[value]="form.controls.password_confirmation.value"
|
||||||
[invalid]="showControlError('password_confirmation')"
|
[invalid]="showControlError('password_confirmation')"
|
||||||
[visible]="passwordVisible()"
|
|
||||||
(valueChange)="updatePassword('password_confirmation', $event)"
|
(valueChange)="updatePassword('password_confirmation', $event)"
|
||||||
(visibleChange)="setPasswordVisibility($event)"
|
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password_confirmation'); as errorMessage) {
|
@if (getControlError('password_confirmation'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
|||||||
@@ -50,43 +50,6 @@ describe('ResetPasswordPageComponent', () => {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
it('shows and hides both password fields with either visibility control', async () => {
|
|
||||||
const modalService = {
|
|
||||||
openSimple: vi.fn(),
|
|
||||||
};
|
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [ResetPasswordPageComponent],
|
|
||||||
providers: resetProviders(modalService),
|
|
||||||
}).compileComponents();
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(ResetPasswordPageComponent);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
const getPasswordInputs = () =>
|
|
||||||
Array.from(fixture.nativeElement.querySelectorAll('input')) as HTMLInputElement[];
|
|
||||||
const getVisibilityButtons = () =>
|
|
||||||
Array.from(
|
|
||||||
fixture.nativeElement.querySelectorAll('button[aria-label]'),
|
|
||||||
) as HTMLButtonElement[];
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
|
||||||
|
|
||||||
getVisibilityButtons()[0].click();
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['text', 'text']);
|
|
||||||
expect(getVisibilityButtons().map((button) => button.getAttribute('aria-label'))).toEqual([
|
|
||||||
'Ocultar contraseña',
|
|
||||||
'Ocultar contraseña',
|
|
||||||
]);
|
|
||||||
|
|
||||||
getVisibilityButtons()[1].click();
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects passwords that do not match', async () => {
|
it('rejects passwords that do not match', async () => {
|
||||||
const modalService = {
|
const modalService = {
|
||||||
openSimple: vi.fn(),
|
openSimple: vi.fn(),
|
||||||
@@ -144,7 +107,7 @@ describe('ResetPasswordPageComponent', () => {
|
|||||||
password_confirmation: 'Secret!123',
|
password_confirmation: 'Secret!123',
|
||||||
});
|
});
|
||||||
expect(modalService.openSimple).toHaveBeenCalledWith({
|
expect(modalService.openSimple).toHaveBeenCalledWith({
|
||||||
title: 'Contraseña modificada correctamente',
|
content: 'Contraseña modificada correctamente',
|
||||||
buttonLabel: 'Cerrar',
|
buttonLabel: 'Cerrar',
|
||||||
});
|
});
|
||||||
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
||||||
|
|||||||
@@ -49,7 +49,6 @@ export class ResetPasswordPageComponent {
|
|||||||
private readonly submittedState = signal(false);
|
private readonly submittedState = signal(false);
|
||||||
private readonly isSubmittingState = signal(false);
|
private readonly isSubmittingState = signal(false);
|
||||||
private readonly serverErrorState = signal<string | null>(null);
|
private readonly serverErrorState = signal<string | null>(null);
|
||||||
private readonly passwordVisibleState = signal(false);
|
|
||||||
|
|
||||||
private readonly email = this.route.snapshot.queryParamMap.get('email') ?? '';
|
private readonly email = this.route.snapshot.queryParamMap.get('email') ?? '';
|
||||||
private readonly code = this.route.snapshot.queryParamMap.get('code') ?? '';
|
private readonly code = this.route.snapshot.queryParamMap.get('code') ?? '';
|
||||||
@@ -73,11 +72,6 @@ export class ResetPasswordPageComponent {
|
|||||||
protected readonly submitted = this.submittedState.asReadonly();
|
protected readonly submitted = this.submittedState.asReadonly();
|
||||||
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
||||||
protected readonly serverError = this.serverErrorState.asReadonly();
|
protected readonly serverError = this.serverErrorState.asReadonly();
|
||||||
protected readonly passwordVisible = this.passwordVisibleState.asReadonly();
|
|
||||||
|
|
||||||
protected setPasswordVisibility(visible: boolean): void {
|
|
||||||
this.passwordVisibleState.set(visible);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected updatePassword(controlName: PasswordControlName, value: string | number): void {
|
protected updatePassword(controlName: PasswordControlName, value: string | number): void {
|
||||||
this.form.controls[controlName].setValue(String(value));
|
this.form.controls[controlName].setValue(String(value));
|
||||||
@@ -155,7 +149,7 @@ export class ResetPasswordPageComponent {
|
|||||||
|
|
||||||
this.modalService
|
this.modalService
|
||||||
.openSimple({
|
.openSimple({
|
||||||
title: 'Contraseña modificada correctamente',
|
content: 'Contraseña modificada correctamente',
|
||||||
buttonLabel: 'Cerrar',
|
buttonLabel: 'Cerrar',
|
||||||
})
|
})
|
||||||
.subscribe(() => {
|
.subscribe(() => {
|
||||||
|
|||||||
@@ -24,10 +24,7 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|||||||
|
|
||||||
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';
|
||||||
import {
|
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||||
CheckoutService,
|
|
||||||
isExpiredStockReservationResponse,
|
|
||||||
} from '../../../../core/services/checkout.service';
|
|
||||||
import {
|
import {
|
||||||
CatalogFeaturedItem,
|
CatalogFeaturedItem,
|
||||||
CatalogFeaturedItems,
|
CatalogFeaturedItems,
|
||||||
@@ -202,20 +199,10 @@ export class SearchPageComponent {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
await this.router.navigate(['/checkout', 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);
|
||||||
const message =
|
this.toastService.danger('No se pudo iniciar la compra directa.');
|
||||||
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
|
||||||
? error.error.message
|
|
||||||
: 'No se pudo iniciar la compra directa.';
|
|
||||||
this.toastService.danger(message);
|
|
||||||
|
|
||||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
|
||||||
this.cartService.loadCart(true).subscribe({
|
|
||||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
this.creatingDirectPurchase.set(false);
|
this.creatingDirectPurchase.set(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
No hay productos disponibles en este momento.
|
No hay productos disponibles en este momento.
|
||||||
</p>
|
</p>
|
||||||
} @else {
|
} @else {
|
||||||
@for (group of catalog(); track group.id; let first = $first) {
|
@for (group of catalog(); track group.id) {
|
||||||
<app-store-section [attr.id]="group.code" [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"
|
||||||
@@ -30,7 +30,6 @@
|
|||||||
[items]="group.items"
|
[items]="group.items"
|
||||||
[loading]="isGroupLoading(group.id)"
|
[loading]="isGroupLoading(group.id)"
|
||||||
[loadImages]="!hasMainCarouselImages() || mainCarouselReady()"
|
[loadImages]="!hasMainCarouselImages() || mainCarouselReady()"
|
||||||
[prioritizeFirstImage]="first && !hasMainCarouselImages()"
|
|
||||||
[unavailableVariantIds]="unavailableVariantIds()"
|
[unavailableVariantIds]="unavailableVariantIds()"
|
||||||
[savingProductIds]="savingProductIds()"
|
[savingProductIds]="savingProductIds()"
|
||||||
(buy)="onBuyProduct($event)"
|
(buy)="onBuyProduct($event)"
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
} from '../../../../core/services/catalog/catalog.interface';
|
} from '../../../../core/services/catalog/catalog.interface';
|
||||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
||||||
|
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||||
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 { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
@@ -83,6 +84,7 @@ const pageOneItems: CatalogFeaturedItem[] = [
|
|||||||
nombre: 'Auriculares Bluetooth',
|
nombre: 'Auriculares Bluetooth',
|
||||||
precio: '24999.00',
|
precio: '24999.00',
|
||||||
image: '/catalog/auriculares.jpg',
|
image: '/catalog/auriculares.jpg',
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
@@ -90,6 +92,7 @@ const pageOneItems: CatalogFeaturedItem[] = [
|
|||||||
nombre: 'Teclado Mecanico',
|
nombre: 'Teclado Mecanico',
|
||||||
precio: '18999.00',
|
precio: '18999.00',
|
||||||
image: null,
|
image: null,
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -107,7 +110,16 @@ function createTenant(extras: Tenant['extras'] = {}): Tenant {
|
|||||||
footer_bg_color: '#ffffff',
|
footer_bg_color: '#ffffff',
|
||||||
header_logo: '/header.png',
|
header_logo: '/header.png',
|
||||||
footer_logo: '/footer.png',
|
footer_logo: '/footer.png',
|
||||||
storefront_website_type_code: 'shopit',
|
website_type_code: 'shopit',
|
||||||
|
website_type: {
|
||||||
|
codigo: 'shopit',
|
||||||
|
nombre: 'ShopIt',
|
||||||
|
primary_color: null,
|
||||||
|
secondary_color: null,
|
||||||
|
danger_color: null,
|
||||||
|
success_color: null,
|
||||||
|
site_logo: null,
|
||||||
|
},
|
||||||
extras,
|
extras,
|
||||||
categories: [],
|
categories: [],
|
||||||
};
|
};
|
||||||
@@ -216,40 +228,42 @@ describe('StoreHomePageComponent', () => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
tenant.event = {
|
tenant.event = {
|
||||||
id: 1,
|
|
||||||
title: 'Fiesta Fútbol Infantil',
|
title: 'Fiesta Fútbol Infantil',
|
||||||
subtitle: null,
|
|
||||||
description: null,
|
|
||||||
location: 'Rosario, Santa Fe',
|
location: 'Rosario, Santa Fe',
|
||||||
date_text: '5 y 6 de Diciembre 2026',
|
|
||||||
social_media: [
|
|
||||||
{
|
|
||||||
code: 'whatsapp',
|
|
||||||
icon: 'fa-brands fa-whatsapp',
|
|
||||||
name: 'WhatsApp',
|
|
||||||
url: 'https://wa.me/5493410000000',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
dates: [
|
dates: [
|
||||||
{
|
{
|
||||||
id: 20,
|
id: 20,
|
||||||
date: '2026-12-05',
|
date: '2026-12-05',
|
||||||
time_start: '09:00:00',
|
time_start: '09:00:00',
|
||||||
time_end: '18:00:00',
|
time_end: '18:00:00',
|
||||||
info_text: null,
|
|
||||||
isCanceled: false,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 21,
|
id: 21,
|
||||||
date: '2026-12-06',
|
date: '2026-12-06',
|
||||||
time_start: '09:00:00',
|
time_start: '09:00:00',
|
||||||
time_end: '18:00:00',
|
time_end: '18:00:00',
|
||||||
info_text: null,
|
|
||||||
isCanceled: false,
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
tenant.storefront_website_type_code = 'onticket';
|
tenant.event_date_text = '5 y 6 de Diciembre 2026';
|
||||||
|
tenant.website_type_code = 'onticket';
|
||||||
|
tenant.social_media = [
|
||||||
|
{
|
||||||
|
code: 'whatsapp',
|
||||||
|
icon: 'fa-brands fa-whatsapp',
|
||||||
|
name: 'WhatsApp',
|
||||||
|
url: 'https://wa.me/5493410000000',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
tenant.website_type = {
|
||||||
|
codigo: 'onticket',
|
||||||
|
nombre: 'OnTicket',
|
||||||
|
primary_color: null,
|
||||||
|
secondary_color: null,
|
||||||
|
danger_color: null,
|
||||||
|
success_color: null,
|
||||||
|
site_logo: null,
|
||||||
|
};
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [StoreHomePageComponent],
|
imports: [StoreHomePageComponent],
|
||||||
@@ -282,7 +296,7 @@ describe('StoreHomePageComponent', () => {
|
|||||||
expect(hero.textContent).toContain('5 y 6 de Diciembre 2026');
|
expect(hero.textContent).toContain('5 y 6 de Diciembre 2026');
|
||||||
const heroComponent = fixture.debugElement.query(By.directive(HeroBannerComponent))
|
const heroComponent = fixture.debugElement.query(By.directive(HeroBannerComponent))
|
||||||
.componentInstance as HeroBannerComponent;
|
.componentInstance as HeroBannerComponent;
|
||||||
expect(heroComponent.eventConfig?.contact).toEqual(tenant.event.social_media);
|
expect(heroComponent.eventConfig?.contact).toEqual(tenant.social_media);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders additional information as an HTML section', async () => {
|
it('renders additional information as an HTML section', async () => {
|
||||||
@@ -350,21 +364,14 @@ describe('StoreHomePageComponent', () => {
|
|||||||
it('renders only the active event data when the tenant does not have the hero extra', async () => {
|
it('renders only the active event data when the tenant does not have the hero extra', async () => {
|
||||||
const tenant = createTenant();
|
const tenant = createTenant();
|
||||||
tenant.event = {
|
tenant.event = {
|
||||||
id: 2,
|
|
||||||
title: 'Fiesta Fútbol Infantil',
|
title: 'Fiesta Fútbol Infantil',
|
||||||
subtitle: null,
|
|
||||||
description: null,
|
|
||||||
location: 'Sunchales, Santa Fe',
|
location: 'Sunchales, Santa Fe',
|
||||||
date_text: null,
|
|
||||||
social_media: [],
|
|
||||||
dates: [
|
dates: [
|
||||||
{
|
{
|
||||||
id: 25,
|
id: 25,
|
||||||
date: '2026-10-09',
|
date: '2026-10-09',
|
||||||
time_start: '09:00:00',
|
time_start: '09:00:00',
|
||||||
time_end: '18:00:00',
|
time_end: '18:00:00',
|
||||||
info_text: null,
|
|
||||||
isCanceled: false,
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
@@ -402,7 +409,14 @@ describe('StoreHomePageComponent', () => {
|
|||||||
|
|
||||||
it('requests another page for the selected featured group', async () => {
|
it('requests another page for the selected featured group', async () => {
|
||||||
const pageTwoItems: CatalogFeaturedItem[] = [
|
const pageTwoItems: CatalogFeaturedItem[] = [
|
||||||
{ id: 3, type: 'product', nombre: 'Mouse Gamer', precio: '15999.00', image: null },
|
{
|
||||||
|
id: 3,
|
||||||
|
type: 'product',
|
||||||
|
nombre: 'Mouse Gamer',
|
||||||
|
precio: '15999.00',
|
||||||
|
image: null,
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
const catalogServiceStub = {
|
const catalogServiceStub = {
|
||||||
getCatalog: vi.fn(),
|
getCatalog: vi.fn(),
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import { TenantService } from '../../../../core/services/tenant.service';
|
|||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import {
|
import {
|
||||||
CheckoutService,
|
CheckoutService,
|
||||||
isExpiredStockReservationResponse,
|
|
||||||
isInsufficientStockResponse,
|
isInsufficientStockResponse,
|
||||||
} from '../../../../core/services/checkout.service';
|
} from '../../../../core/services/checkout.service';
|
||||||
import {
|
import {
|
||||||
@@ -75,23 +74,22 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
|||||||
);
|
);
|
||||||
protected readonly eventConfig = computed(() => {
|
protected readonly eventConfig = computed(() => {
|
||||||
const tenant = this.tenant();
|
const tenant = this.tenant();
|
||||||
|
const contact = tenant?.social_media ?? [];
|
||||||
const event = tenant?.event;
|
const event = tenant?.event;
|
||||||
|
|
||||||
if (event) {
|
if (event) {
|
||||||
return {
|
return {
|
||||||
id: event.id,
|
id: tenant.id,
|
||||||
title: event.title,
|
title: event.title,
|
||||||
location: event.location,
|
location: event.location,
|
||||||
dates_text: event.date_text,
|
dates_text: tenant.event_date_text,
|
||||||
dates: event.dates.map((eventDate) => ({
|
dates: event.dates.map((eventDate) => ({
|
||||||
id: eventDate.id,
|
id: eventDate.id,
|
||||||
date: eventDate.date,
|
date: eventDate.date,
|
||||||
start_time: eventDate.time_start,
|
start_time: eventDate.time_start,
|
||||||
end_time: eventDate.time_end,
|
end_time: eventDate.time_end,
|
||||||
info_text: eventDate.info_text,
|
|
||||||
isCanceled: eventDate.isCanceled,
|
|
||||||
})),
|
})),
|
||||||
contact: event.social_media,
|
contact,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,18 +217,10 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
|||||||
tenant.codigo,
|
tenant.codigo,
|
||||||
reservedCartId !== null ? { cart_id: reservedCartId } : { direct_items: directItems },
|
reservedCartId !== null ? { cart_id: reservedCartId } : { direct_items: directItems },
|
||||||
);
|
);
|
||||||
await this.router.navigate(['/checkout', 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);
|
||||||
|
|
||||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
|
||||||
this.toastService.danger(error.error.message);
|
|
||||||
this.cartService.loadCart(true).subscribe({
|
|
||||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error instanceof HttpErrorResponse && isInsufficientStockResponse(error.error)) {
|
if (error instanceof HttpErrorResponse && isInsufficientStockResponse(error.error)) {
|
||||||
const unavailableIds = error.error.unavailable_items
|
const unavailableIds = error.error.unavailable_items
|
||||||
.map((item) => item.variant_id)
|
.map((item) => item.variant_id)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user