56 Commits

Author SHA1 Message Date
c387a01d62 Merge branch 'fix/TL-1860' into develop 2026-08-28 09:27:59 -03:00
593580d648 fix(store-layout): ensure full width and minimum width for layout components 2026-08-28 09:23:27 -03:00
dbfadf417a refactor(checkout): remove unused completion request 2026-08-27 12:11:16 -03:00
dddb086cd8 refactor(catalog): remove obsolete products request 2026-08-27 12:11:16 -03:00
a825b3693b fix(catalog): refresh after expired cart replacement 2026-08-27 09:54:21 -03:00
679342ec8d fix(checkout): defer catalog refresh for expired reservations 2026-08-27 09:54:15 -03:00
a5420e6a42 feat(checkout): refresh catalog availability on checkout failure 2026-08-27 09:50:33 -03:00
91b8788c91 feat(checkout): implement mobile countdown display and logic 2026-08-27 09:20:24 -03:00
b6a52ceb8c feat(checkout): enhance countdown synchronization and cleanup logic 2026-08-27 09:03:38 -03:00
51d051733c fix(store-layout): update checkout countdown logic and test description 2026-08-27 08:59:41 -03:00
f62cd08807 feat(store-header): display checkout countdown 2026-08-27 08:52:57 -03:00
d61b1e4b0a feat(checkout): synchronize purchase countdown 2026-08-27 08:52:42 -03:00
1bffefece3 fix(store-header): adjust category menu structure and set height for categories 2026-08-27 08:46:53 -03:00
b0d2cd05bc feat(checkout): add completePurchase method and update PurchaseStatusResponse 2026-08-26 17:00:35 -03:00
591f53c102 Squashed commit of the following:
commit 38d03588b1
Merge: 8e987d0 6f4aa3b
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 26 10:25:23 2026 -0300

    Merge branch 'fix/cart-expiration-notification' of https://gitea.quo.ar/tbianchini/shopit-front into fix/cart-expiration-notification

commit 8e987d0ce6
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 26 10:02:26 2026 -0300

    fix(purchase-status): clear cart on approved purchase

commit e171b9a233
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 17:06:07 2026 -0300

    refactor(checkout): use purchase id route segment

commit 643d43adea
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 17:05:59 2026 -0300

    fix(checkout): handle expired purchase exits

commit d89d01b511
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:47:17 2026 -0300

    fix(checkout): refresh expired carts

commit eeb245209b
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:46:12 2026 -0300

    fix(checkout): show backend start errors

commit 9d3754c2d8
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:33:44 2026 -0300

    fix(cart): refresh state after expiration

commit 6f4aa3b1bd
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 26 10:02:26 2026 -0300

    fix(purchase-status): clear cart on approved purchase

commit 2b342ec235
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 17:06:07 2026 -0300

    refactor(checkout): use purchase id route segment

commit d06b146104
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 17:05:59 2026 -0300

    fix(checkout): handle expired purchase exits

commit f4e0a9e028
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:47:17 2026 -0300

    fix(checkout): refresh expired carts

commit 8c2b738806
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:46:12 2026 -0300

    fix(checkout): show backend start errors

commit 1362d0c163
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:33:44 2026 -0300

    fix(cart): refresh state after expiration
2026-08-26 10:29:23 -03:00
85529f40f2 fix(register-page): implement password visibility toggle for registration fields 2026-08-26 10:02:56 -03:00
4a952af784 fix(favicon): update favicon handling to use a default SVG icon 2026-08-25 11:44:24 -03:00
b1d4c4d13d fix(reset-password): implement password visibility toggle for input fields 2026-08-25 11:26:56 -03:00
8861e42fff fix(stepper): add disabled state to prevent navigation and provide visual feedback 2026-08-24 14:07:12 -03:00
7fbdd3844f fix(purchase-detail): add in-review section with WhatsApp contact option 2026-08-24 12:35:33 -03:00
f2c1542e46 fix(purchase-list): refactor purchase list to consolidate in-review and paid purchases, add status message display 2026-08-24 12:35:25 -03:00
def86405dc fix(purchase-list): conditionally render paginator for in-review and paid purchases 2026-08-24 09:17:27 -03:00
870de3ca6e feat(purchase-list): implement pagination for in-review and paid purchases 2026-08-24 09:16:52 -03:00
d8d489e846 fix(checkout): increase polling max attempts for QR and transfer payments 2026-08-22 23:08:20 +00:00
4183d6386d fix(checkout): increase polling max attempts for QR and transfer payments 2026-08-22 23:06:38 +00:00
8089298383 feat(catalog): show product availability tooltips 2026-08-21 16:47:29 -03:00
d51db00247 feat(ui): add reusable information tooltip 2026-08-21 16:47:21 -03:00
88c3a08a23 fix(checkout): lock reviewed payments and refresh cart on exit 2026-08-21 16:16:11 -03:00
21e89805d0 fix(checkout): lock modifications after transfer submission 2026-08-21 15:50:18 -03:00
195ac73aed fix(checkout): disable cart access 2026-08-21 15:50:12 -03:00
c24a8b946d feat(catalog): refresh availability after cart changes 2026-08-21 14:19:32 -03:00
70060f65ec feat(cart): notify catalog availability changes 2026-08-21 14:19:28 -03:00
02ff829c06 refactor(checkout): cancel purchase without reloading cart 2026-08-21 13:42:59 -03:00
69c836a578 refactor(cart): preserve cart when checkout starts 2026-08-21 13:42:59 -03:00
87cc430f05 revert(checkout): keep tenant editing policy contract 2026-08-21 11:09:00 -03:00
3e9e35c681 refactor(checkout): remove purchase item editing client 2026-08-21 11:05:39 -03:00
0bd6dc3b22 fix(checkout): restore cart on every exit 2026-08-21 11:04:09 -03:00
f056c32f49 feat(checkout): improve error handling for expired purchases and refactor toast service usage 2026-08-21 10:29:47 -03:00
11df4dbe72 Merge branch 'feature/restore-cart-on-modify' into develop 2026-08-21 10:14:37 -03:00
9b69a1d387 feat(checkout): add error handling for expired purchases in checkout process 2026-08-21 10:10:20 -03:00
4251ca8a8a fix(checkout): redirect expired purchases from checkout 2026-08-20 17:01:34 -03:00
b14f34d3e8 test(checkout): cover cart restoration before editing 2026-08-20 16:30:09 -03:00
d636b2b82b feat(checkout): restore cart before modifying items 2026-08-20 16:28:58 -03:00
cfa1091116 feat(checkout): enhance payment submission with error handling and polling logic 2026-08-20 15:53:33 -03:00
d0b1607ff4 refactor(checkout): update checkout navigation logic to retain purchase state 2026-08-20 13:53:52 -03:00
92546a28c0 feat(catalog): add anchor IDs to featured groups 2026-08-20 12:46:14 -03:00
ce26fb5d1a feat(tenant): display contact details in store footer 2026-08-20 12:46:14 -03:00
38a57adf55 feat(checkout): implement transfer payment polling with cancellation 2026-08-20 11:09:52 -03:00
e1d9590905 feat(checkout): map editing policy to cart controls 2026-08-20 10:56:33 -03:00
00a01e1a8e feat(cart): open header cart from query param 2026-08-20 10:56:27 -03:00
56e011bc7a feat(cart): update cart layout styles for improved responsiveness and structure 2026-08-20 08:42:41 -03:00
5c6a03b10d feat(catalog): replace stock_tecnico with maximum_addable_quantity across components and services 2026-08-19 17:00:03 -03:00
cc446433f6 Merge branch 'homologacion' 2026-08-19 15:36:19 -03:00
2d0664a7c7 feat(cart): implement cart editing policy with granular permissions 2026-08-19 10:16:06 -03:00
2192eea09f Merge branch 'homologacion' 2026-08-18 17:26:28 -03:00
755d6a9903 feat(angular.json): enhance production and homo configurations with optimization and license extraction 2026-08-18 15:18:01 -03:00
98 changed files with 2891 additions and 687 deletions

View File

@@ -47,6 +47,9 @@
}, },
"configurations": { "configurations": {
"production": { "production": {
"optimization": true,
"extractLicenses": true,
"sourceMap": false,
"budgets": [ "budgets": [
{ {
"type": "initial", "type": "initial",
@@ -84,6 +87,9 @@
] ]
}, },
"homo": { "homo": {
"optimization": true,
"extractLicenses": true,
"sourceMap": false,
"fileReplacements": [ "fileReplacements": [
{ {
"replace": "src/environments/environment.ts", "replace": "src/environments/environment.ts",

View File

@@ -7,6 +7,7 @@ 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';
@@ -97,6 +98,21 @@ 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();
@@ -246,15 +262,33 @@ 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 to /login', async () => { it('redirects unauthenticated users from /checkout/:id to /login', async () => {
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false)); const { router } = await renderAppAt('/checkout/25', createTenantServiceStub(), createAuthServiceStub(false));
expect(router.url).toBe('/login?returnUrl=%2Fcheckout'); expect(router.url).toBe('/login?returnUrl=%2Fcheckout%2F25');
}); });
it('allows authenticated users to access /checkout', async () => { it('allows authenticated users to access /checkout/:id', async () => {
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(true)); const checkoutTenant = {
...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'); expect(router.url).toBe('/checkout/25');
}); });
}); });

View File

@@ -115,6 +115,6 @@ describe('App', () => {
expect(fixture.nativeElement.textContent).toContain('No encontramos una tienda para este dominio'); expect(fixture.nativeElement.textContent).toContain('No encontramos una tienda para este dominio');
expect(document.title).toBe('ShopitFront'); expect(document.title).toBe('ShopitFront');
expect(document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href')) expect(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");
}); });
}); });

View File

@@ -9,6 +9,8 @@ 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, g = 0, b = 0; let r = 0, g = 0, b = 0;
@@ -66,7 +68,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 || 'favicon.ico'; const faviconHref = tenant?.favicon || EMPTY_FAVICON;
this.title.setTitle(siteTitle); this.title.setTitle(siteTitle);

View File

@@ -62,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', tenant); const result = runGuard('checkout', '/checkout/25', 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('/');

View File

@@ -22,14 +22,18 @@
<div class="col-12 col-md-6 col-xl-5 d-grid gap-3 align-content-start store-layout__contact"> <div class="col-12 col-md-6 col-xl-5 d-grid gap-3 align-content-start store-layout__contact">
<div class="d-grid gap-2 store-layout__contact-details"> <div class="d-grid gap-2 store-layout__contact-details">
<div class="d-flex align-items-center gap-2"> @if (address) {
<i class="fa-solid fa-location-dot" aria-hidden="true"></i> <div class="d-flex align-items-center gap-2">
<span>Av. San Lorenzo 1542, Rosario</span> <i class="fa-solid fa-location-dot" aria-hidden="true"></i>
</div> <span>{{ address }}</span>
<div class="d-flex align-items-center gap-2"> </div>
<i class="fa-solid fa-phone" aria-hidden="true"></i> }
<span>54 9 (0341) 6658247</span> @if (phone) {
</div> <div class="d-flex align-items-center gap-2">
<i class="fa-solid fa-phone" aria-hidden="true"></i>
<span>{{ phone }}</span>
</div>
}
</div> </div>
<p class="mb-0 small store-layout__muted-text store-layout__copyright"> <p class="mb-0 small store-layout__muted-text store-layout__copyright">

View File

@@ -27,5 +27,7 @@ export class StoreFooterComponent {
@Input() logoUrl: string | null = null; @Input() logoUrl: string | null = null;
@Input() backgroundImageUrl: string | null = null; @Input() backgroundImageUrl: string | null = null;
@Input() storeName: string | null = null; @Input() storeName: string | null = null;
@Input() address: string | null = null;
@Input() phone: string | null = null;
readonly logoutClick = output<void>(); readonly logoutClick = output<void>();
} }

View File

@@ -79,10 +79,13 @@
@if (displayCart()) { @if (displayCart()) {
<app-cart-icon <app-cart-icon
[quantity]="cartQuantity()" [quantity]="cartDisabled() ? null : cartQuantity()"
ariaLabel="Carrito de compras" [disabled]="cartDisabled()"
title="Carrito" [ariaLabel]="
(click)="cartClick.emit()" cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito de compras'
"
[title]="cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito'"
(click)="onCartClick()"
/> />
} }
@@ -149,9 +152,9 @@
</div> </div>
</div> </div>
@if (displayCategories()) { <div class="store-layout__categories d-none d-md-block">
<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">
<div class="container-xl px-3 px-md-4"> @if (displayCategories()) {
<div class="store-layout__category-menu"> <div class="store-layout__category-menu">
<button <button
type="button" type="button"
@@ -172,7 +175,18 @@
(categorySelect)="onCategorySelect($event)" (categorySelect)="onCategorySelect($event)"
/> />
</div> </div>
</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>
} </div>
</header> </header>

View File

@@ -10,6 +10,26 @@
border-bottom: 1px solid var(--border-color); 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 { .store-layout__brand-slot {
min-width: 150px; min-width: 150px;
} }

View File

@@ -1,4 +1,13 @@
import { Component, ElementRef, HostListener, inject, input, output, signal } from '@angular/core'; import {
Component,
computed,
ElementRef,
HostListener,
inject,
input,
output,
signal,
} from '@angular/core';
import { Router, RouterLink } from '@angular/router'; import { Router, RouterLink } from '@angular/router';
import { AuthUser } from '../../../services/auth/auth.interfaces'; import { AuthUser } from '../../../services/auth/auth.interfaces';
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component'; import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
@@ -39,6 +48,8 @@ export class StoreHeaderComponent {
readonly displayCategories = input(true); readonly displayCategories = input(true);
readonly displaySeachBar = input(true); readonly displaySeachBar = input(true);
readonly displayCart = input(true); readonly displayCart = input(true);
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>();
@@ -52,6 +63,26 @@ export class StoreHeaderComponent {
protected readonly minSearchLength = 3; protected readonly minSearchLength = 3;
protected readonly showSearchError = signal(false); protected readonly showSearchError = signal(false);
protected readonly searchControl = new FormControl('', { nonNullable: true }); 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']) @HostListener('document:click', ['$event'])
protected onDocumentClick(event: MouseEvent): void { protected onDocumentClick(event: MouseEvent): void {

View File

@@ -12,7 +12,9 @@
[displayCategories]="tenant()?.display_categories ?? true" [displayCategories]="tenant()?.display_categories ?? true"
[displaySeachBar]="tenant()?.display_seach_bar ?? true" [displaySeachBar]="tenant()?.display_seach_bar ?? true"
[displayCart]="displayCart()" [displayCart]="displayCart()"
(cartClick)="isCartOpen.set(!isCartOpen())" [cartDisabled]="isCheckoutRoute()"
[checkoutRemainingSeconds]="checkoutRemainingSeconds()"
(cartClick)="onCartClick()"
(ticketsClick)="onTicketsClick()" (ticketsClick)="onTicketsClick()"
(loginClick)="onLoginClick()" (loginClick)="onLoginClick()"
(logoutClick)="onLogoutClick()" (logoutClick)="onLogoutClick()"
@@ -20,7 +22,7 @@
(categorySelect)="onCategorySelect($event)" (categorySelect)="onCategorySelect($event)"
/> />
@if (displayCart() && isCartOpen()) { @if (displayCart() && !isCheckoutRoute() && isCartOpen()) {
<div class="store-layout__cart-overlay" (click)="isCartOpen.set(false)"></div> <div class="store-layout__cart-overlay" (click)="isCartOpen.set(false)"></div>
<div class="store-layout__cart-dropdown card border-0 shadow-lg"> <div class="store-layout__cart-dropdown card border-0 shadow-lg">
<app-cart <app-cart
@@ -29,7 +31,11 @@
[subtotal]="cartSubtotal()" [subtotal]="cartSubtotal()"
[discount]="cartDiscount()" [discount]="cartDiscount()"
[total]="cartTotal()" [total]="cartTotal()"
[readonly]="!cartEditingEnabled()" [readonly]="!canModifyCart()"
[allowModify]="canModifyCart()"
[allowUpdateQuantity]="canUpdateCartQuantity()"
[allowUpdateVariant]="canUpdateCartVariant()"
[allowDelete]="canDeleteCartItems()"
[backgroundColor]="'#ffffff'" [backgroundColor]="'#ffffff'"
(closed)="isCartOpen.set(false)" (closed)="isCartOpen.set(false)"
> >
@@ -63,6 +69,8 @@
[logoUrl]="tenant()?.footer_logo ?? null" [logoUrl]="tenant()?.footer_logo ?? null"
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null" [backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
[storeName]="tenant()?.nombre ?? null" [storeName]="tenant()?.nombre ?? null"
[address]="tenant()?.address ?? null"
[phone]="tenant()?.phone ?? null"
(logoutClick)="onLogoutClick()" (logoutClick)="onLogoutClick()"
/> />
</div> </div>

View File

@@ -1,5 +1,7 @@
: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;
@@ -7,6 +9,8 @@
.store-layout { .store-layout {
position: relative; position: relative;
width: 100%;
min-width: 0;
} }
.store-layout__cart-overlay { .store-layout__cart-overlay {
@@ -21,6 +25,8 @@
.store-layout__cart-dropdown { .store-layout__cart-dropdown {
position: absolute; position: absolute;
display: flex;
flex-direction: column;
top: 100px; top: 100px;
right: calc((100% - 1320px) / 2 + 1.5rem); right: calc((100% - 1320px) / 2 + 1.5rem);
width: 100%; width: 100%;
@@ -34,6 +40,10 @@
overflow: hidden; overflow: hidden;
animation: store-layout-slide-down 0.2s ease-out; animation: store-layout-slide-down 0.2s ease-out;
> app-cart {
min-height: 0;
}
@media (max-width: 1400px) { @media (max-width: 1400px) {
right: 1.5rem; right: 1.5rem;
} }

View File

@@ -1,10 +1,18 @@
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 { provideRouter, Router } from '@angular/router'; import {
ActivatedRoute,
convertToParamMap,
ParamMap,
provideRouter,
Router,
UrlSerializer,
} from '@angular/router';
import { of } from 'rxjs'; import { BehaviorSubject, of } from 'rxjs';
import { Tenant } from '../../services/tenant.interface'; import { Tenant } from '../../services/tenant.interface';
import { TenantService } from '../../services/tenant.service'; import { TenantService } from '../../services/tenant.service';
@@ -16,12 +24,16 @@ 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 { 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';
const tenant: Tenant = { const tenant: Tenant = {
id: 1, id: 1,
codigo: 'test', codigo: 'test',
nombre: 'Test Tenant', nombre: 'Test Tenant',
dominio: 'localhost', dominio: 'localhost',
address: 'Calle Test 123, Rosario',
phone: '+54 341 555 1234',
primary_color: '#6376F3', primary_color: '#6376F3',
secondary_color: '#A0A0A0', secondary_color: '#A0A0A0',
danger_color: '#FF8888', danger_color: '#FF8888',
@@ -32,6 +44,13 @@ const tenant: Tenant = {
footer_logo: 'https://example.com/footer.png', footer_logo: 'https://example.com/footer.png',
header_bg_image: 'https://example.com/header-background.png', header_bg_image: 'https://example.com/header-background.png',
footer_bg_image: 'https://example.com/footer-background.png', footer_bg_image: 'https://example.com/footer-background.png',
cart_editing_policy: {
code: 'full',
allow_modify: true,
allow_delete: true,
allow_update_quantity: true,
allow_update_variant: true,
},
categories: [], categories: [],
menues: [ menues: [
{ {
@@ -132,12 +151,16 @@ 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>;
beforeEach(async () => { beforeEach(async () => {
tenantState = signal<Tenant | null>(tenant); tenantState = signal<Tenant | null>(tenant);
cartState = signal<Cart | null>(null); cartState = signal<Cart | null>(null);
authUserState = signal<AuthUser | null>(null); authUserState = signal<AuthUser | null>(null);
checkoutRemainingSecondsState = signal<number | null>(null);
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
const isAuthenticatedState = signal(false); const isAuthenticatedState = signal(false);
checkoutServiceStub = { checkoutServiceStub = {
startCheckout: vi.fn().mockResolvedValue({ id: 55 }), startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
@@ -147,6 +170,11 @@ describe('StoreLayoutComponent', () => {
imports: [StoreLayoutComponent], imports: [StoreLayoutComponent],
providers: [ providers: [
provideRouter([]), provideRouter([]),
{ provide: UrlSerializer, useClass: TenantUrlSerializer },
{
provide: ActivatedRoute,
useValue: { queryParamMap: queryParamMapState.asObservable() },
},
{ {
provide: TenantService, provide: TenantService,
useValue: { useValue: {
@@ -190,6 +218,12 @@ describe('StoreLayoutComponent', () => {
provide: CheckoutService, provide: CheckoutService,
useValue: checkoutServiceStub, useValue: checkoutServiceStub,
}, },
{
provide: CheckoutCountdownService,
useValue: {
remainingSeconds: checkoutRemainingSecondsState.asReadonly(),
},
},
], ],
}).compileComponents(); }).compileComponents();
}); });
@@ -206,6 +240,62 @@ describe('StoreLayoutComponent', () => {
expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull(); expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull();
}); });
it('opens the cart when requested through the openCart query parameter', () => {
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
queryParamMapState.next(convertToParamMap({ openCart: 'true' }));
fixture.detectChanges();
expect((fixture.componentInstance as any).isCartOpen()).toBe(true);
expect((fixture.nativeElement as HTMLElement).querySelector('app-cart')).not.toBeNull();
});
it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => {
tenantState.set({ ...tenant, base_path: 'fiesta' });
const router = TestBed.inject(Router);
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout/25');
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
const cartButton = element.querySelector<HTMLButtonElement>('app-cart-icon button');
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
expect(cartButton?.disabled).toBe(true);
expect(cartButton?.getAttribute('aria-label')).toBe(
'Carrito no disponible durante el checkout',
);
expect(element.querySelector('[data-testid="cart-badge"]')).toBeNull();
header.componentInstance.cartClick.emit();
queryParamMapState.next(convertToParamMap({ openCart: 'true' }));
fixture.detectChanges();
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
expect(element.querySelector('app-cart')).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,
@@ -267,6 +357,12 @@ describe('StoreLayoutComponent', () => {
expect(compiled.querySelector('.fa-whatsapp')).not.toBeNull(); expect(compiled.querySelector('.fa-whatsapp')).not.toBeNull();
expect(compiled.querySelector('.fa-facebook')).not.toBeNull(); expect(compiled.querySelector('.fa-facebook')).not.toBeNull();
expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull(); expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull();
expect(compiled.querySelector('.store-layout__contact-details')?.textContent).toContain(
tenant.address,
);
expect(compiled.querySelector('.store-layout__contact-details')?.textContent).toContain(
tenant.phone,
);
}); });
it('navigates to search results when the search button is clicked', () => { it('navigates to search results when the search button is clicked', () => {
@@ -517,7 +613,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?purchase=25'); vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout/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);
@@ -604,12 +700,44 @@ describe('StoreLayoutComponent', () => {
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', { expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
cart_id: 1, cart_id: 1,
}); });
expect(router.navigate).toHaveBeenCalledWith(['/checkout'], { expect(router.navigate).toHaveBeenCalledWith(['/checkout', 55]);
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,
@@ -647,7 +775,16 @@ describe('StoreLayoutComponent', () => {
}); });
it('hides quantity selectors when the tenant disables cart editing', () => { it('hides quantity selectors when the tenant disables cart editing', () => {
tenantState.set({ ...tenant, cart_editing_enabled: false }); tenantState.set({
...tenant,
cart_editing_policy: {
code: 'disabled',
allow_modify: false,
allow_delete: false,
allow_update_quantity: false,
allow_update_variant: false,
},
});
cartState.set({ cartState.set({
id: 1, id: 1,
tenant_codigo: tenant.codigo, tenant_codigo: tenant.codigo,
@@ -676,4 +813,62 @@ describe('StoreLayoutComponent', () => {
expect(cartItem.componentInstance.readonly()).toBe(true); expect(cartItem.componentInstance.readonly()).toBe(true);
expect(cartItem.nativeElement.querySelector('app-quantity-selector')).toBeNull(); expect(cartItem.nativeElement.querySelector('app-quantity-selector')).toBeNull();
}); });
it('shows variant selectors only for the full cart editing policy', () => {
const variantCart: Cart = {
id: 1,
tenant_codigo: tenant.codigo,
status: 'active',
subtotal: '100.00',
items: [
{
id: 1,
cantidad: 1,
precio_unitario: '100.00',
catalog_item_id: 1,
variant_id: 10,
nombre: 'Producto',
imagen: null,
variant: { id: 10, precio: '100.00', stock_tecnico: 5, values: { talle: 'M' } },
variants: [
{ id: 10, precio: '100.00', stock_tecnico: 5, values: { talle: 'M' } },
{ id: 11, precio: '100.00', stock_tecnico: 5, values: { talle: 'L' } },
],
},
],
};
tenantState.set({
...tenant,
cart_editing_policy: {
code: 'quantity_and_remove',
allow_modify: true,
allow_delete: true,
allow_update_quantity: true,
allow_update_variant: false,
},
});
cartState.set(variantCart);
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
(fixture.componentInstance as any).isCartOpen.set(true);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('app-variant-selector')).toBeNull();
expect(fixture.nativeElement.querySelector('app-quantity-selector')).not.toBeNull();
tenantState.set({
...tenant,
cart_editing_policy: {
code: 'full',
allow_modify: true,
allow_delete: true,
allow_update_quantity: true,
allow_update_variant: true,
},
});
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('app-variant-selector')).not.toBeNull();
});
}); });

View File

@@ -1,5 +1,14 @@
import { Component, computed, inject, OnInit, signal } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http';
import { Router, RouterOutlet } from '@angular/router'; import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
ActivatedRoute,
NavigationEnd,
PRIMARY_OUTLET,
Router,
RouterOutlet,
} from '@angular/router';
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';
@@ -9,9 +18,13 @@ 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 { CheckoutService } from '../../services/checkout.service'; import {
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';
@Component({ @Component({
selector: 'app-store-layout', selector: 'app-store-layout',
@@ -30,14 +43,29 @@ 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 destroyRef = inject(DestroyRef);
protected readonly isCartOpen = signal(false); protected readonly isCartOpen = signal(false);
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(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 cartEditingEnabled = computed( protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
() => this.tenant()?.cart_editing_enabled ?? true, protected readonly canModifyCart = computed(
() => this.cartEditingPolicy()?.allow_modify ?? false,
);
protected readonly canDeleteCartItems = computed(
() => this.cartEditingPolicy()?.allow_delete ?? false,
);
protected readonly canUpdateCartQuantity = computed(
() => this.cartEditingPolicy()?.allow_update_quantity ?? false,
);
protected readonly canUpdateCartVariant = computed(
() => this.cartEditingPolicy()?.allow_update_variant ?? false,
); );
protected readonly cartSubtotal = computed(() => { protected readonly cartSubtotal = computed(() => {
@@ -92,6 +120,7 @@ export class StoreLayoutComponent implements OnInit {
attributes, attributes,
quantity: item.cantidad, quantity: item.cantidad,
variantId: item.variant_id, variantId: item.variant_id,
variants: item.variants,
}; };
} }
@@ -135,15 +164,49 @@ export class StoreLayoutComponent implements OnInit {
}); });
ngOnInit(): void { ngOnInit(): void {
this.router.events
.pipe(
filter((event): event is NavigationEnd => event instanceof NavigationEnd),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((event) => {
const isCheckoutRoute = this.isCheckoutUrl(event.urlAfterRedirects);
this.isCheckoutRoute.set(isCheckoutRoute);
if (isCheckoutRoute) {
this.isCartOpen.set(false);
}
});
this.route.queryParamMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
if (params.get('openCart') === 'true' && !this.isCheckoutRoute()) {
this.isCartOpen.set(true);
}
});
this.cartService.loadCart().subscribe({ this.cartService.loadCart().subscribe({
error: (err) => console.error('Error loading cart', err), error: (err) => console.error('Error loading cart', err),
}); });
} }
private isCheckoutUrl(url: string): boolean {
const primarySegments = this.router.parseUrl(url).root.children[PRIMARY_OUTLET]?.segments ?? [];
return primarySegments[0]?.path === 'checkout';
}
protected onLoginClick(): void { protected onLoginClick(): void {
void this.router.navigate(['/login']); void this.router.navigate(['/login']);
} }
protected onCartClick(): void {
if (this.isCheckoutRoute()) {
return;
}
this.isCartOpen.update((isOpen) => !isOpen);
}
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 },
@@ -167,8 +230,8 @@ export class StoreLayoutComponent implements OnInit {
protected async onLogoutClick(): Promise<void> { protected async onLogoutClick(): Promise<void> {
const isLeavingCheckout = this.router.url.startsWith('/checkout'); const isLeavingCheckout = this.router.url.startsWith('/checkout');
// Checkout must be left while the authenticated session is still valid so // Leave checkout before closing the authenticated session so its component
// its CanDeactivate guard can cancel the pending purchase. // can stop payment polling cleanly. The checkout itself remains pending.
if (isLeavingCheckout) { if (isLeavingCheckout) {
const navigationSucceeded = await this.router.navigate(['/']); const navigationSucceeded = await this.router.navigate(['/']);
@@ -216,14 +279,21 @@ export class StoreLayoutComponent implements OnInit {
cart_id: cart.id, cart_id: cart.id,
}); });
this.cartService.clearCart();
this.isCartOpen.set(false); this.isCartOpen.set(false);
await this.router.navigate(['/checkout'], { await this.router.navigate(['/checkout', purchase.id]);
queryParams: { purchase: purchase.id },
});
} catch (error) { } catch (error) {
console.error('Failed to create cart purchase:', error); console.error('Failed to create cart purchase:', error);
this.toastService.danger('No se pudo iniciar la compra.'); const message =
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);
} }

View File

@@ -24,12 +24,12 @@ describe('auth guards', () => {
}); });
const result = TestBed.runInInjectionContext(() => const result = TestBed.runInInjectionContext(() =>
authGuard(null as never, { url: '/checkout?mode=direct' } as never), authGuard(null as never, { url: '/checkout/25' } 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%3Fmode%3Ddirect', '/login?returnUrl=%2Fcheckout%2F25',
); );
}); });
@@ -39,7 +39,7 @@ describe('auth guards', () => {
}); });
const result = TestBed.runInInjectionContext(() => const result = TestBed.runInInjectionContext(() =>
authGuard(null as never, { url: '/checkout' } as never), authGuard(null as never, { url: '/checkout/25' } as never),
); );
expect(result).toBe(true); expect(result).toBe(true);

View File

@@ -24,6 +24,7 @@ export interface CartItem {
nombre: string | null; nombre: string | null;
imagen: string | null; imagen: string | null;
variant: CartItemVariant | null; variant: CartItemVariant | null;
variants?: CartItemVariant[];
} }
export interface Cart { export interface Cart {

View File

@@ -7,11 +7,13 @@ import { CartService } from './cart.service';
import { TenantService } from '../tenant.service'; import { TenantService } from '../tenant.service';
import { Cart } from './cart.interface'; import { Cart } from './cart.interface';
import { LOADING_MODE } from '../global-loading/loading-mode'; import { LOADING_MODE } from '../global-loading/loading-mode';
import { CatalogAvailabilityService } from '../catalog/catalog-availability.service';
describe('CartService', () => { describe('CartService', () => {
let service: CartService; let service: CartService;
let httpMock: HttpTestingController; let httpMock: HttpTestingController;
let tenantServiceMock: any; let tenantServiceMock: any;
let catalogAvailabilityService: CatalogAvailabilityService;
const mockCart: Cart = { const mockCart: Cart = {
id: 123, id: 123,
@@ -53,6 +55,7 @@ describe('CartService', () => {
}); });
service = TestBed.inject(CartService); service = TestBed.inject(CartService);
catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
httpMock = TestBed.inject(HttpTestingController); httpMock = TestBed.inject(HttpTestingController);
}); });
@@ -80,6 +83,20 @@ 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();
@@ -101,6 +118,9 @@ describe('CartService', () => {
}); });
it('should add item and update signal', () => { it('should add item and update signal', () => {
const availabilityChanged = vi.fn();
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
service.addItem(5, 10, 2).subscribe((res) => { service.addItem(5, 10, 2).subscribe((res) => {
expect(res.data).toEqual(mockCart); expect(res.data).toEqual(mockCart);
expect(service.cart()).toEqual(mockCart); expect(service.cart()).toEqual(mockCart);
@@ -115,9 +135,13 @@ describe('CartService', () => {
}); });
expect(req.request.withCredentials).toBe(true); expect(req.request.withCredentials).toBe(true);
req.flush({ data: mockCart }); req.flush({ data: mockCart });
expect(availabilityChanged).toHaveBeenCalledOnce();
}); });
it('should update item quantity and update signal', () => { it('should update item quantity and update signal', () => {
const availabilityChanged = vi.fn();
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
const updatedCart = { ...mockCart, subtotal: '30.00' }; const updatedCart = { ...mockCart, subtotal: '30.00' };
updatedCart.items[0].cantidad = 3; updatedCart.items[0].cantidad = 3;
@@ -131,9 +155,13 @@ describe('CartService', () => {
expect(req.request.body).toEqual({ cantidad: 3 }); expect(req.request.body).toEqual({ cantidad: 3 });
expect(req.request.withCredentials).toBe(true); expect(req.request.withCredentials).toBe(true);
req.flush({ data: updatedCart }); req.flush({ data: updatedCart });
expect(availabilityChanged).toHaveBeenCalledOnce();
}); });
it('should remove item and update signal', () => { it('should remove item and update signal', () => {
const availabilityChanged = vi.fn();
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
const emptyCart: Cart = { const emptyCart: Cart = {
id: 123, id: 123,
tenant_codigo: 'acme', tenant_codigo: 'acme',
@@ -151,5 +179,18 @@ describe('CartService', () => {
expect(req.request.method).toBe('DELETE'); expect(req.request.method).toBe('DELETE');
expect(req.request.withCredentials).toBe(true); expect(req.request.withCredentials).toBe(true);
req.flush({ data: emptyCart }); req.flush({ data: emptyCart });
expect(availabilityChanged).toHaveBeenCalledOnce();
});
it('does not notify an availability change when a cart mutation fails', () => {
const availabilityChanged = vi.fn();
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
service.removeItem(10).subscribe({ error: vi.fn() });
const req = httpMock.expectOne('http://api.test/tenants/acme/cart/items/10');
req.flush({ message: 'Error' }, { status: 500, statusText: 'Server Error' });
expect(availabilityChanged).not.toHaveBeenCalled();
}); });
}); });

View File

@@ -3,6 +3,7 @@ import { catchError, map, Observable, tap } from 'rxjs';
import { ApiResponse } from '../api-response.interface'; import { ApiResponse } from '../api-response.interface';
import { BaseApiService } from '../base-api.service'; import { BaseApiService } from '../base-api.service';
import { CatalogAvailabilityService } from '../catalog/catalog-availability.service';
import { TenantService } from '../tenant.service'; import { TenantService } from '../tenant.service';
import { Cart } from './cart.interface'; import { Cart } from './cart.interface';
@@ -10,6 +11,7 @@ import { Cart } from './cart.interface';
providedIn: 'root', providedIn: 'root',
}) })
export class CartService extends BaseApiService { export class CartService extends BaseApiService {
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
private readonly tenantService = inject(TenantService); private readonly tenantService = inject(TenantService);
private readonly cartState = signal<Cart | null>(null); private readonly cartState = signal<Cart | null>(null);
@@ -32,14 +34,19 @@ export class CartService extends BaseApiService {
}); });
} }
loadCart(): Observable<Cart> { loadCart(refreshCatalogAvailability = false): 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) => this.cartState.set(cart)), tap((cart) => {
this.cartState.set(cart);
if (refreshCatalogAvailability) {
this.catalogAvailabilityService.notifyAvailabilityChanged();
}
}),
); );
} }
@@ -60,6 +67,7 @@ export class CartService extends BaseApiService {
.pipe( .pipe(
tap((response) => { tap((response) => {
this.cartState.set(response.data); this.cartState.set(response.data);
this.catalogAvailabilityService.notifyAvailabilityChanged();
this.isUpdatingState.set(false); this.isUpdatingState.set(false);
}), }),
catchError((error) => { catchError((error) => {
@@ -93,6 +101,7 @@ export class CartService extends BaseApiService {
.pipe( .pipe(
tap((response) => { tap((response) => {
this.cartState.set(response.data); this.cartState.set(response.data);
this.catalogAvailabilityService.notifyAvailabilityChanged();
this.isUpdatingState.set(false); this.isUpdatingState.set(false);
}), }),
catchError((error) => { catchError((error) => {
@@ -111,6 +120,7 @@ export class CartService extends BaseApiService {
.pipe( .pipe(
tap((response) => { tap((response) => {
this.cartState.set(response.data); this.cartState.set(response.data);
this.catalogAvailabilityService.notifyAvailabilityChanged();
this.isUpdatingState.set(false); this.isUpdatingState.set(false);
}), }),
catchError((error) => { catchError((error) => {

View File

@@ -0,0 +1,15 @@
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class CatalogAvailabilityService {
private readonly availabilityChangedSubject = new Subject<void>();
readonly availabilityChanged$: Observable<void> = this.availabilityChangedSubject.asObservable();
notifyAvailabilityChanged(): void {
this.availabilityChangedSubject.next();
}
}

View File

@@ -66,7 +66,8 @@ export interface CatalogItemVariant {
event_date_id?: number | null; event_date_id?: number | null;
event_date_ids?: number[]; event_date_ids?: number[];
event_dates?: string[]; event_dates?: string[];
stock_tecnico: number | null; maximum_addable_quantity?: number | null;
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;
@@ -98,7 +99,7 @@ export interface CatalogItemDetail {
attributes: ProductAttribute[]; attributes: ProductAttribute[];
variants: CatalogItemVariant[]; variants: CatalogItemVariant[];
selected_variant?: SelectedCatalogItemVariant; selected_variant?: SelectedCatalogItemVariant;
stock_tecnico?: number | null; maximum_addable_quantity?: number | null;
images?: string[]; images?: string[];
} }
@@ -113,7 +114,8 @@ export interface CatalogFeaturedItemVariant {
id: number; id: number;
descripcion?: string | null; descripcion?: string | null;
precio?: string; precio?: string;
stock_tecnico: number | null; maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
values: Record<string, CatalogVariantValue>; values: Record<string, CatalogVariantValue>;
} }
@@ -145,7 +147,8 @@ export interface CatalogFeaturedItem {
descripcion?: string | null; descripcion?: string | null;
precio: number | string; precio: number | string;
image?: string | null; image?: string | null;
stock_tecnico?: number | null; maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
variants?: CatalogFeaturedItemVariant[]; variants?: CatalogFeaturedItemVariant[];
} }
@@ -155,6 +158,7 @@ export type CatalogFeaturedItems =
export interface CatalogFeaturedGroup { export interface CatalogFeaturedGroup {
id: number; id: number;
code: string;
title: string; title: string;
layout: CatalogProductLayout; layout: CatalogProductLayout;
group_layout: CatalogGroupLayout; group_layout: CatalogGroupLayout;

View File

@@ -14,7 +14,6 @@ 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)[];
@@ -33,12 +32,6 @@ 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`);
} }

View File

@@ -0,0 +1,69 @@
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);
});
});

View File

@@ -0,0 +1,97 @@
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;
}
}
}

View File

@@ -1,9 +1,10 @@
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 } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } 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', () => {
@@ -38,4 +39,59 @@ 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);
});
}); });

View File

@@ -1,8 +1,11 @@
import { Injectable } from '@angular/core'; import { inject, 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 { 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;
@@ -43,6 +46,21 @@ 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;
@@ -53,6 +71,9 @@ 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;
} }
export interface PurchaseSummaryResponse extends PurchaseStatusResponse { export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
@@ -89,7 +110,6 @@ 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;
@@ -107,24 +127,34 @@ 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> {
const response = await firstValueFrom( try {
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>( const response = await firstValueFrom(
`${environment.url}tenants/${tenantCode}/compras/start-checkout`, this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
payload, `${environment.url}tenants/${tenantCode}/compras/start-checkout`,
), payload,
); ),
);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response); const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase?.id) { if (!purchase?.id) {
throw new Error('Error al crear la compra.'); throw new Error('Error al crear la compra.');
}
return purchase;
} catch (error) {
const responseBody = (error as { error?: unknown } | null)?.error;
if (!isExpiredStockReservationResponse(responseBody)) {
this.catalogAvailabilityService.notifyAvailabilityChanged();
}
throw error;
} }
return purchase;
} }
async generatePaymentIntent( async generatePaymentIntent(
@@ -169,65 +199,6 @@ export class CheckoutService extends BaseApiService {
return purchase; return purchase;
} }
async updateItemQuantity(
tenantCode: string,
purchaseId: number,
itemId: number,
quantity: number,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom(
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
{ quantity },
),
);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase) {
throw new Error('Error al actualizar la cantidad del producto.');
}
return purchase;
}
async prepareItemEditing(
tenantCode: string,
purchaseId: number,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom(
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/edit-items`,
{},
),
);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase) {
throw new Error('Error al preparar la compra para editarla.');
}
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,
@@ -244,7 +215,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 { status: purchase.status ?? null }; return purchase;
} }
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> { async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
@@ -260,18 +231,26 @@ export class CheckoutService extends BaseApiService {
throw new Error('Error al cancelar la compra.'); throw new Error('Error al cancelar la compra.');
} }
return { status: purchase.status ?? null }; return purchase;
} }
async getPurchases( async getPurchases(
tenantCode: string, tenantCode: string,
status?: string, status?: string,
): Promise<{ data: PurchaseSummaryResponse[] }> { pagination: ApiPaginationQueryParams = {},
let url = `${environment.url}tenants/${tenantCode}/compras`; ): Promise<ApiPaginatedResponse<PurchaseSummaryResponse[]>> {
if (status) { const params: Record<string, string | number> = {};
url += `?status=${status}`;
} if (status) params['status'] = status;
const response = await firstValueFrom(this.http.get<{ data: PurchaseSummaryResponse[] }>(url)); if (pagination.page) params['page'] = pagination.page;
if (pagination.per_page) params['per_page'] = pagination.per_page;
const response = await firstValueFrom(
this.http.get<ApiPaginatedResponse<PurchaseSummaryResponse[]>>(
`${environment.url}tenants/${tenantCode}/compras`,
{ params },
),
);
if (!response) { if (!response) {
throw new Error('Error al obtener las compras.'); throw new Error('Error al obtener las compras.');
} }

View File

@@ -1,5 +1,15 @@
import { ApiResponse } from './api-response.interface'; import { ApiResponse } from './api-response.interface';
export type CartEditingPolicyCode = 'disabled' | 'quantity_and_remove' | 'full';
export interface CartEditingPolicy {
code: CartEditingPolicyCode;
allow_modify: boolean;
allow_delete: boolean;
allow_update_quantity: boolean;
allow_update_variant: boolean;
}
export interface BankAccount { export interface BankAccount {
id: number; id: number;
tenant_code: string; tenant_code: string;
@@ -103,6 +113,8 @@ export interface Tenant {
dominio: string; dominio: string;
base_path?: string; base_path?: string;
site_title?: string | null; site_title?: string | null;
address?: string | null;
phone?: string | null;
favicon?: string | null; favicon?: string | null;
primary_color: string; primary_color: string;
secondary_color: string; secondary_color: string;
@@ -127,7 +139,8 @@ export interface Tenant {
display_categories?: boolean; display_categories?: boolean;
display_seach_bar?: boolean; display_seach_bar?: boolean;
display_cart?: boolean; display_cart?: boolean;
cart_editing_enabled?: boolean; cart_editing_policy?: CartEditingPolicy;
checkout_editing_policy?: CartEditingPolicy;
display_cart_item_images?: boolean; display_cart_item_images?: boolean;
social_media?: SocialMedia[]; social_media?: SocialMedia[];
menues?: Menu[]; menues?: Menu[];

View File

@@ -232,7 +232,7 @@ export class ReutilizablesTestPageComponent {
{ {
id: 1001, id: 1001,
precio: 250000, precio: 250000,
stock_tecnico: 1, maximum_addable_quantity: 1,
values: { values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'), tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'), sector: ticketOption('a', 'Sector A'),
@@ -243,7 +243,7 @@ export class ReutilizablesTestPageComponent {
{ {
id: 1002, id: 1002,
precio: 250000, precio: 250000,
stock_tecnico: 1, maximum_addable_quantity: 1,
values: { values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'), tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'), sector: ticketOption('a', 'Sector A'),
@@ -254,7 +254,7 @@ export class ReutilizablesTestPageComponent {
{ {
id: 1003, id: 1003,
precio: 250000, precio: 250000,
stock_tecnico: 1, maximum_addable_quantity: 1,
values: { values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'), tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('c', 'Sector C'), sector: ticketOption('c', 'Sector C'),
@@ -265,7 +265,7 @@ export class ReutilizablesTestPageComponent {
{ {
id: 1004, id: 1004,
precio: 200000, precio: 200000,
stock_tecnico: 1, maximum_addable_quantity: 1,
values: { values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'), tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'), sector: ticketOption('a', 'Sector A'),
@@ -276,7 +276,7 @@ export class ReutilizablesTestPageComponent {
{ {
id: 1005, id: 1005,
precio: 200000, precio: 200000,
stock_tecnico: 0, maximum_addable_quantity: 0,
values: { values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'), tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'), sector: ticketOption('a', 'Sector A'),
@@ -287,7 +287,7 @@ export class ReutilizablesTestPageComponent {
{ {
id: 1006, id: 1006,
precio: 100000, precio: 100000,
stock_tecnico: 1, maximum_addable_quantity: 1,
values: { values: {
tipo: ticketOption('general', 'General'), tipo: ticketOption('general', 'General'),
sector: ticketOption('b', 'Sector B'), sector: ticketOption('b', 'Sector B'),
@@ -298,7 +298,7 @@ export class ReutilizablesTestPageComponent {
{ {
id: 1007, id: 1007,
precio: 100000, precio: 100000,
stock_tecnico: 1, maximum_addable_quantity: 1,
values: { values: {
tipo: ticketOption('general', 'General'), tipo: ticketOption('general', 'General'),
sector: ticketOption('b', 'Sector B'), sector: ticketOption('b', 'Sector B'),
@@ -309,7 +309,7 @@ export class ReutilizablesTestPageComponent {
{ {
id: 1008, id: 1008,
precio: 90000, precio: 90000,
stock_tecnico: 1, maximum_addable_quantity: 1,
values: { values: {
tipo: ticketOption('general', 'General'), tipo: ticketOption('general', 'General'),
sector: ticketOption('d', 'Sector D'), sector: ticketOption('d', 'Sector D'),
@@ -320,7 +320,7 @@ export class ReutilizablesTestPageComponent {
{ {
id: 1009, id: 1009,
precio: 65000, precio: 65000,
stock_tecnico: 1, maximum_addable_quantity: 1,
values: { values: {
tipo: ticketOption('general', 'General'), tipo: ticketOption('general', 'General'),
sector: ticketOption('d', 'Sector D'), sector: ticketOption('d', 'Sector D'),
@@ -331,7 +331,7 @@ export class ReutilizablesTestPageComponent {
{ {
id: 1010, id: 1010,
precio: 40000, precio: 40000,
stock_tecnico: 1, maximum_addable_quantity: 1,
values: { values: {
tipo: ticketOption('general', 'General'), tipo: ticketOption('general', 'General'),
sector: ticketOption('d', 'Sector D'), sector: ticketOption('d', 'Sector D'),

View File

@@ -11,7 +11,7 @@
.menu-content-section__header { .menu-content-section__header {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0.75rem; gap: var(--menu-content-prefix-gap, 0.75rem);
margin-bottom: 1.25rem; margin-bottom: 1.25rem;
} }

View File

@@ -31,7 +31,7 @@ describe('ProductAttributeSelectorComponent', () => {
fixture.componentRef.setInput('variants', [ fixture.componentRef.setInput('variants', [
{ {
id: 1, id: 1,
stock_tecnico: null, maximum_addable_quantity: null,
values: { size: 'S' }, values: { size: 'S' },
}, },
]); ]);
@@ -51,12 +51,12 @@ describe('ProductAttributeSelectorComponent', () => {
fixture.componentRef.setInput('variants', [ fixture.componentRef.setInput('variants', [
{ {
id: 1, id: 1,
stock_tecnico: 0, maximum_addable_quantity: 0,
values: { size: 'S' }, values: { size: 'S' },
}, },
{ {
id: 2, id: 2,
stock_tecnico: 2, maximum_addable_quantity: 2,
values: { size: 'M' }, values: { size: 'M' },
}, },
]); ]);
@@ -92,9 +92,9 @@ describe('ProductAttributeSelectorComponent', () => {
]); ]);
fixture.componentRef.setInput('inventoryPolicy', 'unlimited'); fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
fixture.componentRef.setInput('variants', [ fixture.componentRef.setInput('variants', [
{ id: 1, stock_tecnico: null, values: { event_date: '1' } }, { id: 1, maximum_addable_quantity: null, values: { event_date: '1' } },
{ id: 2, stock_tecnico: null, values: { event_date: '2' } }, { id: 2, maximum_addable_quantity: null, values: { event_date: '2' } },
{ id: 3, stock_tecnico: null, values: { event_date: ['1', '2'] } }, { id: 3, maximum_addable_quantity: null, values: { event_date: ['1', '2'] } },
]); ]);
fixture.detectChanges(); fixture.detectChanges();
@@ -135,8 +135,8 @@ describe('ProductAttributeSelectorComponent', () => {
]); ]);
fixture.componentRef.setInput('inventoryPolicy', 'unlimited'); fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
fixture.componentRef.setInput('variants', [ fixture.componentRef.setInput('variants', [
{ id: 1, stock_tecnico: null, values: { size: 'S', internal_type: 'adult' } }, { id: 1, maximum_addable_quantity: null, values: { size: 'S', internal_type: 'adult' } },
{ id: 2, stock_tecnico: null, values: { size: 'M', internal_type: 'child' } }, { id: 2, maximum_addable_quantity: null, values: { size: 'M', internal_type: 'child' } },
]); ]);
fixture.detectChanges(); fixture.detectChanges();

View File

@@ -227,7 +227,7 @@ export class ProductAttributeSelectorComponent {
} }
private isVariantAvailable(variant: CatalogItemVariant): boolean { private isVariantAvailable(variant: CatalogItemVariant): boolean {
return this.inventoryPolicy() === 'unlimited' || (variant.stock_tecnico ?? 0) > 0; return variant.maximum_addable_quantity !== 0;
} }
private findFirstHexValue(value: unknown): string | null { private findFirstHexValue(value: unknown): string | null {

View File

@@ -1,11 +1,29 @@
<div class="purchase-item" [routerLink]="[purchase.id]" style="cursor: pointer;"> <div class="purchase-item" [routerLink]="[purchase.id]">
<div class="purchase-info"> <div class="purchase-info">
<span class="purchase-id">Compra {{ purchase.id }}.</span> <span class="purchase-id">Compra {{ purchase.id }}.</span>
<span class="purchase-date">Fecha de compra: {{ purchase.date }}</span> <span class="purchase-date">Fecha de compra: {{ purchase.date }}</span>
</div> </div>
<div class="purchase-action">
<svg width="8" height="14" viewBox="0 0 8 14" fill="none" xmlns="http://www.w3.org/2000/svg" class="arrow-icon"> @if (purchase.statusMessage) {
<path d="M1 1L7 7L1 13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <span class="purchase-status">{{ purchase.statusMessage }}</span>
</svg> }
</div>
</div> <div class="purchase-action">
<svg
width="8"
height="14"
viewBox="0 0 8 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
class="arrow-icon"
>
<path
d="M1 1L7 7L1 13"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</div>
</div>

View File

@@ -2,33 +2,57 @@
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
padding: 16px; gap: 16px;
padding-left:0; padding: 16px;
transition: box-shadow 0.2s, border-radius 0.2s; padding-left: 0;
transition:
box-shadow 0.2s,
border-radius 0.2s;
cursor: pointer; cursor: pointer;
} }
.purchase-item:hover { .purchase-item:hover {
box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.07); box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.07);
border-radius: 8px; border-radius: 8px;
} }
.purchase-item:hover .arrow-icon { .purchase-item:hover .arrow-icon {
color: #5b75ff; /* Blue on hover */ color: var(--color-primary, var(--tenant-primary, #5b75ff));
} }
.purchase-info { .purchase-info {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 4px; gap: 4px;
} }
.purchase-id { .purchase-id {
font-weight: bold; font-weight: bold;
color: #666666; color: #666666;
font-size: 13px; font-size: 13px;
} }
.purchase-date { .purchase-date {
font-weight: 325; font-weight: 325;
color: #666666; color: #666666;
font-size: 10px; font-size: 10px;
} }
.purchase-status {
margin-left: auto;
margin-right: 20px;
color: var(--color-primary, var(--tenant-primary, #5b75ff));
font-size: 16px;
font-weight: 700;
text-align: right;
}
.purchase-action {
display: flex;
flex-shrink: 0;
align-items: center;
}
.arrow-icon { .arrow-icon {
width: 8px; width: 8px;
height: 14px; height: 14px;

View File

@@ -9,6 +9,5 @@ import { RouterLink } from '@angular/router';
styleUrl: './purchase-list-item.scss', styleUrl: './purchase-list-item.scss',
}) })
export class PurchaseListItem { export class PurchaseListItem {
@Input() purchase!: { id: number; date: string }; @Input() purchase!: { id: number; date: string; statusMessage?: string | null };
} }

View File

@@ -1,29 +1,36 @@
<div class="purchase-list-container"> <div class="purchase-list-container">
<ng-container *ngIf="isLoading(); else contentTpl"> @if (isLoading()) {
<!-- Skeleton --> @for (i of [1, 2, 3, 4]; track i) {
<div class="skeleton-item" *ngFor="let i of [1, 2, 3, 4]"> <div class="skeleton-item">
<div class="skeleton-info"> <div class="skeleton-info">
<div class="skeleton-id"></div> <div class="skeleton-id"></div>
<div class="skeleton-date"></div> <div class="skeleton-date"></div>
</div>
<div class="skeleton-action"></div>
</div> </div>
</ng-container> <div class="skeleton-action"></div>
</div>
}
} @else {
@if (purchases().length > 0) {
@for (purchase of purchases(); track purchase.id; let last = $last) {
<app-purchase-list-item [purchase]="purchase"></app-purchase-list-item>
@if (!last) {
<div class="purchase-divider"></div>
}
}
} @else {
<div class="empty-state">Aún no hay compras realizadas</div>
}
<ng-template #contentTpl> @if (pagination(); as paginationData) {
<ng-container *ngIf="purchases().length > 0; else emptyTpl"> @if (paginationData.last_page > 1) {
<ng-container *ngFor="let purchase of purchases(); let last = last"> <app-paginator
<app-purchase-list-item class="purchase-list__paginator"
[purchase]="purchase"> [page]="paginationData.current_page"
</app-purchase-list-item> [totalPages]="paginationData.last_page"
<div class="purchase-divider" *ngIf="!last"></div> [disabled]="isLoading()"
</ng-container> (pageChange)="onPageChange($event)"
</ng-container> ></app-paginator>
</ng-template> }
}
<ng-template #emptyTpl> }
<div class="empty-state"> </div>
Aún no hay compras realizadas
</div>
</ng-template>
</div>

View File

@@ -4,9 +4,14 @@
width: 100%; width: 100%;
} }
.purchase-list__paginator {
align-self: center;
margin-top: 1.5rem;
}
.purchase-divider { .purchase-divider {
height: 1px; height: 1px;
background-color: #DDDDDD; background-color: #dddddd;
width: 100%; width: 100%;
} }
@@ -39,7 +44,7 @@
.skeleton-id { .skeleton-id {
width: 100px; width: 100px;
height: 1rem; height: 1rem;
background-color: #EEEEEE; background-color: #eeeeee;
border-radius: 4px; border-radius: 4px;
animation: pulse 1.5s infinite ease-in-out; animation: pulse 1.5s infinite ease-in-out;
} }
@@ -47,7 +52,7 @@
.skeleton-date { .skeleton-date {
width: 150px; width: 150px;
height: 0.8rem; height: 0.8rem;
background-color: #EEEEEE; background-color: #eeeeee;
border-radius: 4px; border-radius: 4px;
animation: pulse 1.5s infinite ease-in-out; animation: pulse 1.5s infinite ease-in-out;
} }
@@ -55,19 +60,19 @@
.skeleton-action { .skeleton-action {
width: 24px; width: 24px;
height: 24px; height: 24px;
background-color: #EEEEEE; background-color: #eeeeee;
border-radius: 50%; border-radius: 50%;
animation: pulse 1.5s infinite ease-in-out; animation: pulse 1.5s infinite ease-in-out;
} }
@keyframes pulse { @keyframes pulse {
0% { 0% {
background-color: #EEEEEE; background-color: #eeeeee;
} }
50% { 50% {
background-color: #E0E0E0; background-color: #e0e0e0;
} }
100% { 100% {
background-color: #EEEEEE; background-color: #eeeeee;
} }
} }

View File

@@ -1,19 +1,24 @@
import { Component, OnInit, inject, signal } from '@angular/core'; import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PurchaseListItem } from '../purchase-list-item/purchase-list-item'; import { PurchaseListItem } from '../purchase-list-item/purchase-list-item';
import { CheckoutService, PurchaseSummaryResponse } from '../../../../../../core/services/checkout.service'; import {
CheckoutService,
PurchaseSummaryResponse,
} from '../../../../../../core/services/checkout.service';
import { ToastService } from '../../../../../../core/services/toast.service'; import { ToastService } from '../../../../../../core/services/toast.service';
import { TenantService } from '../../../../../../core/services/tenant.service'; import { TenantService } from '../../../../../../core/services/tenant.service';
import { ApiPaginationMeta } from '../../../../../../core/services/api-paginated-response.interface';
import { PaginatorComponent } from '../../../../../../shared/components/paginator/paginator.component';
type PurchaseListViewModel = { type PurchaseListViewModel = {
id: number; id: number;
date: string; date: string;
statusMessage: string | null;
}; };
@Component({ @Component({
selector: 'app-purchase-list', selector: 'app-purchase-list',
standalone: true, standalone: true,
imports: [CommonModule, PurchaseListItem], imports: [PurchaseListItem, PaginatorComponent],
templateUrl: './purchase-list.html', templateUrl: './purchase-list.html',
styleUrl: './purchase-list.scss', styleUrl: './purchase-list.scss',
}) })
@@ -22,21 +27,28 @@ export class PurchaseList implements OnInit {
private readonly toastService = inject(ToastService); private readonly toastService = inject(ToastService);
private readonly tenantService = inject(TenantService); private readonly tenantService = inject(TenantService);
purchases = signal<PurchaseListViewModel[]>([]); protected readonly purchases = signal<PurchaseListViewModel[]>([]);
isLoading = signal<boolean>(true); protected readonly pagination = signal<ApiPaginationMeta | null>(null);
protected readonly isLoading = signal(true);
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
await this.loadPurchases();
}
protected async onPageChange(page: number): Promise<void> {
await this.loadPurchases(page);
}
private async loadPurchases(page = 1): Promise<void> {
this.isLoading.set(true);
try { try {
const tenantCode = this.tenantService.tenant()?.codigo || '';
const response = await this.checkoutService const response = await this.checkoutService
.withCustomLoading() .withCustomLoading()
.getPurchases(tenantCode, 'paid'); .getPurchases(this.tenantCode(), 'paid,in_review', { page });
const mappedPurchases = response.data.map((purchase: PurchaseSummaryResponse) => ({
id: purchase.id, this.purchases.set(this.mapPurchases(response.data));
date: this.formatDate(purchase.created_at), this.pagination.set(response.meta);
}));
this.purchases.set(mappedPurchases);
} catch (error) { } catch (error) {
this.toastService.danger('Hubo un error al cargar las compras'); this.toastService.danger('Hubo un error al cargar las compras');
} finally { } finally {
@@ -44,6 +56,18 @@ export class PurchaseList implements OnInit {
} }
} }
private tenantCode(): string {
return this.tenantService.tenant()?.codigo || '';
}
private mapPurchases(purchases: PurchaseSummaryResponse[]): PurchaseListViewModel[] {
return purchases.map((purchase) => ({
id: purchase.id,
date: this.formatDate(purchase.created_at),
statusMessage: purchase.status === 'in_review' ? 'Esperando confirmación' : null,
}));
}
private formatDate(value: string | null): string { private formatDate(value: string | null): string {
if (!value) { if (!value) {
return '-'; return '-';

View File

@@ -15,6 +15,27 @@
@if (isLoading()) { @if (isLoading()) {
<p class="purchase-loading">Cargando detalle de compra...</p> <p class="purchase-loading">Cargando detalle de compra...</p>
} @else if (purchase(); as purchase) { } @else if (purchase(); as purchase) {
@if (purchase.isInReview) {
<section class="purchase-review" aria-labelledby="purchase-review-title">
<h3 id="purchase-review-title" class="purchase-review__title">ESPERANDO CONFIRMACIÓN</h3>
<p class="purchase-review__message">
Tu compra aún no ha sido confirmada.<br />
Si no te contactaste con nosotros, podés hacerlo a través del siguiente WhatsApp
</p>
@if (whatsappUrl()) {
<app-button
type="button"
variant="primary"
hostClass="purchase-review__button"
(click)="openWhatsApp()"
>
WhatsApp
</app-button>
}
</section>
}
<div <div
class="d-flex justify-content-between align-items-center mb-4 pb-3" class="d-flex justify-content-between align-items-center mb-4 pb-3"
style="border-bottom: 1px solid #dddddd" style="border-bottom: 1px solid #dddddd"

View File

@@ -4,6 +4,8 @@
} }
.account-page { .account-page {
--menu-content-prefix-gap: 0;
display: block; display: block;
width: 100%; width: 100%;
max-width: 600px; max-width: 600px;
@@ -50,6 +52,32 @@
font-size: 17px; font-size: 17px;
} }
.purchase-review {
padding-bottom: 2rem;
margin-bottom: 2rem;
border-bottom: 1px solid #dddddd;
}
.purchase-review__title {
margin: 0 0 0.5rem;
color: var(--color-primary, var(--tenant-primary, #5b75ff));
font-size: 14px;
font-weight: 700;
line-height: 1.25;
}
.purchase-review__message {
margin: 0 0 1.5rem;
color: #777777;
font-size: 12px;
font-weight: 400;
line-height: 1.4;
}
.purchase-review__button {
width: 185px;
}
.purchase-loading, .purchase-loading,
.purchase-empty { .purchase-empty {
color: #666666; color: #666666;

View File

@@ -1,5 +1,4 @@
import { CommonModule } from '@angular/common'; import { Component, OnInit, computed, inject, signal } from '@angular/core';
import { Component, OnInit, inject, signal } from '@angular/core';
import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { import {
@@ -8,6 +7,7 @@ import {
} from '../../../../../../core/services/checkout.service'; } from '../../../../../../core/services/checkout.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 { ButtonComponent } from '../../../../../../shared/components/button/button.component';
import { MenuContentSectionComponent } from '../../../../components/menu-content-section/menu-content-section.component'; import { MenuContentSectionComponent } from '../../../../components/menu-content-section/menu-content-section.component';
import { PurchaseItem, PurchaseItemViewModel } from '../../components/purchase-item/purchase-item'; import { PurchaseItem, PurchaseItemViewModel } from '../../components/purchase-item/purchase-item';
@@ -16,12 +16,13 @@ type PurchaseDetailViewModel = {
date: string; date: string;
total: string; total: string;
items: PurchaseItemViewModel[]; items: PurchaseItemViewModel[];
isInReview: boolean;
}; };
@Component({ @Component({
selector: 'app-purchase-detail-page', selector: 'app-purchase-detail-page',
standalone: true, standalone: true,
imports: [CommonModule, RouterLink, PurchaseItem, MenuContentSectionComponent], imports: [RouterLink, PurchaseItem, MenuContentSectionComponent, ButtonComponent],
templateUrl: './purchase-detail-page.html', templateUrl: './purchase-detail-page.html',
styleUrl: './purchase-detail-page.scss', styleUrl: './purchase-detail-page.scss',
}) })
@@ -34,6 +35,12 @@ export class PurchaseDetailPage implements OnInit {
readonly isLoading = signal(true); readonly isLoading = signal(true);
readonly purchase = signal<PurchaseDetailViewModel | null>(null); readonly purchase = signal<PurchaseDetailViewModel | null>(null);
protected readonly whatsappUrl = computed(
() =>
this.tenantService
.tenant()
?.social_media?.find((socialMedia) => socialMedia.code === 'whatsapp')?.url ?? null,
);
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
const purchaseId = this.route.snapshot.paramMap.get('id'); const purchaseId = this.route.snapshot.paramMap.get('id');
@@ -54,6 +61,7 @@ export class PurchaseDetailPage implements OnInit {
date: this.formatDate(response.created_at), date: this.formatDate(response.created_at),
total: response.total, total: response.total,
items: this.mapItems(response), items: this.mapItems(response),
isInReview: response.status === 'in_review',
}); });
} catch (error) { } catch (error) {
console.error('Failed to fetch purchase detail:', error); console.error('Failed to fetch purchase detail:', error);
@@ -64,6 +72,14 @@ export class PurchaseDetailPage implements OnInit {
} }
} }
protected openWhatsApp(): void {
const url = this.whatsappUrl();
if (url) {
window.open(url, '_blank', 'noopener,noreferrer');
}
}
private formatDate(value: string | null): string { private formatDate(value: string | null): string {
if (!value) { if (!value) {
return '-'; return '-';

View File

@@ -7,6 +7,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
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 { 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';
@@ -107,6 +108,16 @@ describe('CategoryItemsPageComponent', () => {
expect(Array.isArray(productList.items())).toBe(false); expect(Array.isArray(productList.items())).toBe(false);
}); });
it('reloads the current category page when catalog availability changes', () => {
const fixture = TestBed.createComponent(CategoryItemsPageComponent);
fixture.detectChanges();
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
expect(getCategoryItems).toHaveBeenCalledTimes(2);
expect(getCategoryItems).toHaveBeenLastCalledWith(7, { page: 1 });
});
it('does not request the API when the category id is invalid', () => { it('does not request the API when the category id is invalid', () => {
TestBed.overrideProvider(ActivatedRoute, { TestBed.overrideProvider(ActivatedRoute, {
useValue: { useValue: {

View File

@@ -16,18 +16,23 @@ import {
finalize, finalize,
map, map,
of, of,
startWith,
switchMap, switchMap,
tap, tap,
} from 'rxjs'; } from 'rxjs';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
import { CheckoutService } from '../../../../core/services/checkout.service'; import {
CheckoutService,
isExpiredStockReservationResponse,
} from '../../../../core/services/checkout.service';
import { import {
CatalogGroupLayout, CatalogGroupLayout,
CategoryItemsResponse, CategoryItemsResponse,
} 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 { 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 { import {
@@ -50,6 +55,7 @@ interface CategoryRouteState {
}) })
export class CategoryItemsPageComponent { export class CategoryItemsPageComponent {
private readonly cartService = inject(CartService); private readonly cartService = inject(CartService);
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
private readonly catalogService = inject(CatalogService); private readonly catalogService = inject(CatalogService);
private readonly injector = inject(Injector); private readonly injector = inject(Injector);
private readonly destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
@@ -65,22 +71,29 @@ export class CategoryItemsPageComponent {
protected readonly paginatedLayout: CatalogGroupLayout = 'paginated'; protected readonly paginatedLayout: CatalogGroupLayout = 'paginated';
constructor() { constructor() {
combineLatest([this.route.paramMap, this.route.queryParamMap]) const routeState$ = combineLatest([this.route.paramMap, this.route.queryParamMap]).pipe(
.pipe( map(
map( ([params, queryParams]): CategoryRouteState => ({
([params, queryParams]): CategoryRouteState => ({ categoryId: this.parsePositiveInteger(params.get('id')),
categoryId: this.parsePositiveInteger(params.get('id')), page: this.parsePositiveInteger(queryParams.get('page'), 1),
page: this.parsePositiveInteger(queryParams.get('page'), 1),
}),
),
distinctUntilChanged(
(previous, current) =>
previous.categoryId === current.categoryId && previous.page === current.page,
),
tap(() => {
this.results.set(null);
this.error.set(null);
}), }),
),
distinctUntilChanged(
(previous, current) =>
previous.categoryId === current.categoryId && previous.page === current.page,
),
tap(() => {
this.results.set(null);
this.error.set(null);
}),
);
combineLatest([
routeState$,
this.catalogAvailabilityService.availabilityChanged$.pipe(startWith(undefined)),
])
.pipe(
map(([routeState]) => routeState),
switchMap(({ categoryId, page }) => { switchMap(({ categoryId, page }) => {
if (categoryId === 0) { if (categoryId === 0) {
this.error.set('La categoría solicitada no es válida.'); this.error.set('La categoría solicitada no es válida.');
@@ -157,10 +170,20 @@ export class CategoryItemsPageComponent {
], ],
}, },
); );
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } }); await this.router.navigate(['/checkout', purchase.id]);
} catch (error) { } catch (error) {
console.error('Failed to create direct purchase:', error); console.error('Failed to create direct purchase:', error);
this.toastService.danger('No se pudo iniciar la compra directa.'); const message =
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
? error.error.message
: 'No se pudo iniciar la compra directa.';
this.toastService.danger(message);
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);
} }

View File

@@ -5,13 +5,12 @@
</div> </div>
} @else { } @else {
<div class="checkout-page"> <div class="checkout-page">
<div <div class="checkout-page__stepper-col">
class="checkout-page__stepper-col" <app-stepper
[class.checkout-page__stepper-col--editing]="isEditingItems()" #stepper
[attr.aria-hidden]="isEditingItems()" [initialStepIndex]="checkoutStepIndex()"
[attr.inert]="isEditingItems() ? '' : null" [disabled]="hasSubmittedTransfer()"
> >
<app-stepper #stepper [initialStepIndex]="checkoutStepIndex()">
<app-step label="Datos" [isValid]="isStep1Valid()"> <app-step label="Datos" [isValid]="isStep1Valid()">
<app-checkout-data-step <app-checkout-data-step
[form]="form" [form]="form"
@@ -24,6 +23,7 @@
<app-checkout-payment-step <app-checkout-payment-step
[paymentMethods]="paymentMethods" [paymentMethods]="paymentMethods"
[selectedPaymentMethod]="selectedPaymentMethod()" [selectedPaymentMethod]="selectedPaymentMethod()"
[paymentMethodDisabled]="hasSubmittedTransfer()"
[copiedTransferField]="copiedTransferField()" [copiedTransferField]="copiedTransferField()"
[transferAccount]="transferAccount()" [transferAccount]="transferAccount()"
[transferDni]="transferDni()" [transferDni]="transferDni()"
@@ -45,30 +45,31 @@
</app-stepper> </app-stepper>
</div> </div>
@if (isEditingItems()) {
<div class="checkout-page__editing-notice" role="status">
<p>Terminá de modificar las cantidades para continuar con el pago.</p>
</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()"
[subtotal]="cartSubtotal()" [subtotal]="cartSubtotal()"
[discount]="cartDiscount()" [discount]="cartDiscount()"
[total]="cartTotal()" [total]="cartTotal()"
[readonly]="!cartEditingEnabled()" [readonly]="true"
[allowEditing]=" [allowModify]="true"
createdPurchase()?.status === 'created' || createdPurchase()?.status === 'pending_payment' [showModifyWhenReadonly]="true"
" [modifyAsAction]="true"
[allowRemove]="false" [editingDisabled]="isPurchaseModificationDisabled()"
[persistQuantityChanges]="false"
[editing]="isEditingItems()"
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"
backgroundColor="transparent" backgroundColor="transparent"
(editingChange)="onEditingItemsChange($event)" (modify)="onModifyPurchase()"
(itemQuantityChange)="onPurchaseItemQuantityChange($event)"
/> />
</div> </div>
</div> </div>

View File

@@ -11,8 +11,7 @@
order: 1; order: 1;
} }
.checkout-page__stepper-col, .checkout-page__stepper-col {
.checkout-page__editing-notice {
order: 2; order: 2;
} }
} }
@@ -21,27 +20,6 @@
min-width: 0; min-width: 0;
border-radius: 4px; border-radius: 4px;
min-height: 420px; min-height: 420px;
&--editing {
display: none;
}
}
&__editing-notice {
display: grid;
min-height: 420px;
place-items: center;
padding: 2rem;
border-radius: 4px;
background: #f5f5f5;
color: #666666;
text-align: center;
p {
max-width: 360px;
margin: 0;
font-size: 14px;
}
} }
&__cart-col { &__cart-col {
@@ -50,6 +28,24 @@
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 {

View File

@@ -1,3 +1,4 @@
import { HttpErrorResponse } from '@angular/common/http';
import { signal } from '@angular/core'; import { signal } from '@angular/core';
import { getTestBed, TestBed } from '@angular/core/testing'; import { getTestBed, TestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing'; import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
@@ -6,33 +7,41 @@ import { of } from 'rxjs';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
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 { CheckoutService } from '../../../../core/services/checkout.service'; import { CheckoutService } from '../../../../core/services/checkout.service';
import { CatalogService } from '../../../../core/services/catalog/catalog.service'; import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service';
import { CartService } from '../../../../core/services/cart/cart.service';
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', () => {
let checkoutServiceStub: { let checkoutServiceStub: {
startCheckout: ReturnType<typeof vi.fn>; startCheckout: ReturnType<typeof vi.fn>;
updateCustomerData: ReturnType<typeof vi.fn>; updateCustomerData: ReturnType<typeof vi.fn>;
updateItemQuantity: ReturnType<typeof vi.fn>;
prepareItemEditing: ReturnType<typeof vi.fn>;
cancelPurchase: ReturnType<typeof vi.fn>; cancelPurchase: ReturnType<typeof vi.fn>;
generatePaymentIntent: ReturnType<typeof vi.fn>; generatePaymentIntent: ReturnType<typeof vi.fn>;
submitPurchaseForReview: ReturnType<typeof vi.fn>;
getPurchase: ReturnType<typeof vi.fn>; getPurchase: ReturnType<typeof vi.fn>;
withCustomLoading: ReturnType<typeof vi.fn>; withCustomLoading: ReturnType<typeof vi.fn>;
}; };
let cartServiceStub: {
cart: ReturnType<typeof signal>;
isUpdating: ReturnType<typeof signal<boolean>>;
loadCart: ReturnType<typeof vi.fn>;
clearCart: ReturnType<typeof vi.fn>;
};
let routerStub: { navigate: ReturnType<typeof vi.fn> }; let routerStub: { navigate: ReturnType<typeof vi.fn> };
let routeQueryParamMap: ReturnType<typeof convertToParamMap>; let toastServiceStub: { danger: ReturnType<typeof vi.fn> };
let globalLoadingServiceStub: {
start: ReturnType<typeof vi.fn>;
stop: ReturnType<typeof vi.fn>;
};
let cartServiceStub: { loadCart: ReturnType<typeof vi.fn> };
let routeParamMap: ReturnType<typeof convertToParamMap>;
let authUserState: ReturnType<typeof signal>; let authUserState: ReturnType<typeof signal>;
let tenantState: ReturnType<typeof signal<{ codigo: string; cart_editing_enabled?: boolean }>>; let tenantState: ReturnType<
typeof signal<{
codigo: string;
checkout_editing_policy?: CartEditingPolicy;
}>
>;
beforeAll(() => { beforeAll(() => {
try { try {
@@ -53,56 +62,50 @@ describe('CheckoutPageComponent payment validation', () => {
total: '0.00', total: '0.00',
}), }),
updateCustomerData: vi.fn(), updateCustomerData: vi.fn(),
updateItemQuantity: vi.fn(),
prepareItemEditing: vi.fn(),
cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }), cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }),
generatePaymentIntent: vi.fn().mockResolvedValue({ generatePaymentIntent: vi.fn().mockResolvedValue({
qr_data: { qr_code: 'qr-value' }, qr_data: { qr_code: 'qr-value' },
}), }),
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'in_review' }),
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }), getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
withCustomLoading: vi.fn(), withCustomLoading: vi.fn(),
}; };
checkoutServiceStub.withCustomLoading.mockReturnValue(checkoutServiceStub); checkoutServiceStub.withCustomLoading.mockReturnValue(checkoutServiceStub);
cartServiceStub = {
cart: signal({
id: 10,
tenant_codigo: 'tenant-test',
status: 'active',
items: [],
subtotal: '0.00',
}),
isUpdating: signal(false),
loadCart: vi.fn().mockReturnValue(of({})),
clearCart: vi.fn(),
};
cartServiceStub.clearCart.mockImplementation(() => {
cartServiceStub.cart.set({
id: null,
tenant_codigo: 'tenant-test',
status: 'active',
items: [],
subtotal: '0.00',
});
});
routerStub = { navigate: vi.fn() }; routerStub = { navigate: vi.fn() };
routeQueryParamMap = convertToParamMap({}); toastServiceStub = { danger: vi.fn() };
globalLoadingServiceStub = { start: vi.fn(), stop: vi.fn() };
cartServiceStub = {
loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })),
};
routeParamMap = convertToParamMap({});
authUserState = signal(null); authUserState = signal(null);
tenantState = signal({ codigo: 'tenant-test' }); tenantState = signal({
codigo: 'tenant-test',
checkout_editing_policy: {
code: 'full',
allow_modify: true,
allow_delete: true,
allow_update_quantity: true,
allow_update_variant: true,
},
});
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [CheckoutPageComponent], imports: [CheckoutPageComponent],
providers: [ providers: [
{ provide: CheckoutService, useValue: checkoutServiceStub }, { provide: CheckoutService, useValue: checkoutServiceStub },
{ provide: CatalogService, useValue: { getCatalogItem: vi.fn() } }, { provide: CatalogService, useValue: { getCatalogItem: vi.fn() } },
{ provide: CartService, useValue: cartServiceStub },
{ provide: TenantService, useValue: { tenant: tenantState } }, { provide: TenantService, useValue: { tenant: tenantState } },
{ provide: AuthService, useValue: { user: authUserState } }, { provide: AuthService, useValue: { user: authUserState } },
{ provide: GlobalLoadingService, useValue: globalLoadingServiceStub },
{ provide: ToastService, useValue: toastServiceStub },
{ provide: CartService, useValue: cartServiceStub },
{ {
provide: ActivatedRoute, provide: ActivatedRoute,
useValue: { useValue: {
snapshot: { snapshot: {
get queryParamMap() { get paramMap() {
return routeQueryParamMap; return routeParamMap;
}, },
}, },
}, },
@@ -127,6 +130,35 @@ 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('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' })
@@ -142,7 +174,6 @@ describe('CheckoutPageComponent payment validation', () => {
await vi.advanceTimersByTimeAsync(5_000); await vi.advanceTimersByTimeAsync(5_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(2); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(2);
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledTimes(1); expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledTimes(1);
}); });
@@ -194,19 +225,46 @@ describe('CheckoutPageComponent payment validation', () => {
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled(); expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
}); });
it('checks the purchase detail once when the transfer was made', 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');
await component.onComplete(); await component.onComplete();
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25); expect(component.transferValidationStatus()).toBe('checking');
expect(component.transferValidationStatus()).toBe('error'); expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
expect(cartServiceStub.clearCart).not.toHaveBeenCalled(); expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
expect(routerStub.navigate).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(30_000); for (let attempt = 1; attempt <= 3; attempt += 1) {
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(1); await vi.advanceTimersByTimeAsync(3_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(attempt);
expect(component.transferValidationStatus()).toBe('checking');
}
await vi.advanceTimersByTimeAsync(3_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
expect(component.transferValidationStatus()).toBe('error');
expect(routerStub.navigate).not.toHaveBeenCalled();
});
it('prevents modifying the purchase after Ya transferí is clicked', async () => {
const { component } = createComponent();
component.selectedPaymentMethod.set('transfer');
await component.onComplete();
expect(component.hasSubmittedTransfer()).toBe(true);
expect(component.isPurchaseModificationDisabled()).toBe(true);
await component.selectPaymentMethod('qr');
await component.onModifyPurchase();
expect(component.selectedPaymentMethod()).toBe('transfer');
expect(checkoutServiceStub.generatePaymentIntent).not.toHaveBeenCalled();
expect(checkoutServiceStub.cancelPurchase).not.toHaveBeenCalled();
expect(globalLoadingServiceStub.start).not.toHaveBeenCalled();
expect(routerStub.navigate).not.toHaveBeenCalled();
}); });
it('navigates after a transfer is confirmed as paid', async () => { it('navigates after a transfer is confirmed as paid', async () => {
@@ -215,25 +273,49 @@ describe('CheckoutPageComponent payment validation', () => {
component.selectedPaymentMethod.set('transfer'); component.selectedPaymentMethod.set('transfer');
await component.onComplete(); await component.onComplete();
await vi.advanceTimersByTimeAsync(3_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
}); });
it('shows a retryable state when transfer validation fails', async () => { it('keeps polling after transfer validation requests fail', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined); vi.spyOn(console, 'error').mockImplementation(() => undefined);
checkoutServiceStub.getPurchase.mockRejectedValue(new Error('network error')); checkoutServiceStub.getPurchase.mockRejectedValue(new Error('network error'));
const { component } = createComponent(); const { component } = createComponent();
component.selectedPaymentMethod.set('transfer'); component.selectedPaymentMethod.set('transfer');
await component.onComplete(); await component.onComplete();
await vi.advanceTimersByTimeAsync(12_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
expect(component.transferValidationStatus()).toBe('error'); expect(component.transferValidationStatus()).toBe('error');
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(routerStub.navigate).not.toHaveBeenCalled();
}); });
it('does not poll when submitting a transfer for review fails', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined);
checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error'));
const { component } = createComponent();
component.selectedPaymentMethod.set('transfer');
await component.onComplete();
await vi.advanceTimersByTimeAsync(12_000);
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
expect(component.transferValidationStatus()).toBe('error');
});
it('cancels transfer polling when the component is destroyed', async () => {
const checkout = createComponent();
checkout.component.selectedPaymentMethod.set('transfer');
await checkout.component.onComplete();
checkout.fixture.destroy();
await vi.advanceTimersByTimeAsync(12_000);
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
});
it('loads purchase items but prefills customer data from the user', async () => { it('loads purchase items but prefills customer data from the user', async () => {
const purchase = { const purchase = {
id: 25, id: 25,
@@ -265,7 +347,7 @@ describe('CheckoutPageComponent payment validation', () => {
subtotal: '2501.00', subtotal: '2501.00',
total: '2501.00', total: '2501.00',
}; };
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue(purchase); checkoutServiceStub.getPurchase.mockResolvedValue(purchase);
authUserState.set({ authUserState.set({
id: 7, id: 7,
@@ -302,7 +384,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;
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockReturnValue( checkoutServiceStub.getPurchase.mockReturnValue(
new Promise((resolve) => { new Promise((resolve) => {
resolvePurchase = resolve; resolvePurchase = resolve;
@@ -323,12 +405,13 @@ 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 () => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status: 'pending_payment', status: 'pending_payment',
@@ -348,7 +431,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 () => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status: 'pending_payment', status: 'pending_payment',
@@ -372,7 +455,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) => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status, status,
@@ -390,7 +473,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 () => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status: 'pending_payment', status: 'pending_payment',
@@ -408,73 +491,75 @@ describe('CheckoutPageComponent payment validation', () => {
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
}); });
it('updates a purchase item while editing and refreshes checkout totals', async () => { it('shows the API error and redirects to status when cancellation finds an expired purchase', async () => {
const updatedPurchase = { const message = 'La compra venció. Iniciá una nueva compra.';
id: 25, checkoutServiceStub.cancelPurchase.mockRejectedValue({
items: [], error: { code: 'purchase.expired', message },
subtotal: '300.00',
total: '300.00',
};
checkoutServiceStub.updateItemQuantity.mockResolvedValue(updatedPurchase);
const { component } = createComponent();
component.isEditingItems.set(true);
await component.onPurchaseItemQuantityChange({
item: {
cartItemId: 91,
imageUrl: null,
product: 'Remera',
originalPrice: null,
discountedPrice: 100,
discountPercentage: null,
attributes: [],
quantity: 2,
},
quantity: 3,
}); });
const { component } = createComponent();
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith('tenant-test', 25, 91, 3); await component.onModifyPurchase();
expect(component.createdPurchase()).toBe(updatedPurchase);
expect(component.isUpdatingItem()).toBe(false); expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
queryParams: { status: 'expired' },
});
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
expect(component.isCancellingPurchase()).toBe(false);
}); });
it('keeps the payment step selected while editing and regenerates payment afterward', async () => { it('cancels the current purchase and opens the active cart when Modificar is clicked', async () => {
const editablePurchase = { let finishNavigation!: (navigated: boolean) => void;
routerStub.navigate.mockReturnValue(
new Promise<boolean>((resolve) => {
finishNavigation = resolve;
}),
);
const { component } = createComponent();
component.createdPurchase.set({
id: 25, id: 25,
status: 'created', status: 'created',
items: [], items: [
subtotal: '100.00', {
total: '100.00', id: 91,
}; quantity: 2,
checkoutServiceStub.prepareItemEditing.mockResolvedValue(editablePurchase); unit_price: '100.00',
const { component } = createComponent(); line_total: '200.00',
component.stepper = { currentStepIndex: signal(1) }; source_catalog_item_id: 8,
const selectPaymentMethod = vi source_variant_id: null,
.spyOn(component, 'selectPaymentMethod') item_details: {
.mockResolvedValue(undefined); nombre: 'Remera',
descripcion: null,
slug: 'remera',
imagen: null,
attributes: [],
},
},
],
subtotal: '200.00',
total: '200.00',
});
const modification = component.onModifyPurchase();
await Promise.resolve();
await Promise.resolve();
await component.onEditingItemsChange(true); expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
expect(globalLoadingServiceStub.stop).not.toHaveBeenCalled();
expect(component.createdPurchaseId()).toBeNull();
expect(component.createdPurchase()).toBeNull();
expect(routerStub.navigate).toHaveBeenCalledWith(['/'], {
queryParams: { openCart: true },
});
expect(checkoutServiceStub.prepareItemEditing).toHaveBeenCalledWith('tenant-test', 25); finishNavigation(true);
expect(component.isEditingItems()).toBe(true); await modification;
expect(component.createdPurchase()).toBe(editablePurchase);
await component.onEditingItemsChange(false); expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
expect(component.stepper.currentStepIndex()).toBe(1); await component.canDeactivate();
expect(selectPaymentMethod).toHaveBeenCalledWith('qr');
expect(component.isEditingItems()).toBe(false);
});
it('does not allow item editing when the tenant disables cart editing', async () => {
tenantState.set({ codigo: 'tenant-test', cart_editing_enabled: false });
const { component } = createComponent();
await component.onEditingItemsChange(true);
expect(component.cartEditingEnabled()).toBe(false);
expect(component.isEditingItems()).toBe(false);
expect(checkoutServiceStub.prepareItemEditing).not.toHaveBeenCalled();
}); });
it('updates customer data on the existing purchase before payment', async () => { it('updates customer data on the existing purchase before payment', async () => {
@@ -511,14 +596,122 @@ describe('CheckoutPageComponent payment validation', () => {
expect(component.stepper.next).toHaveBeenCalledOnce(); expect(component.stepper.next).toHaveBeenCalledOnce();
}); });
it('cancels the pending purchase before allowing navigation away', async () => { it('cancels the current purchase when navigating away from checkout', async () => {
const { component } = createComponent(); const { component } = createComponent();
await expect(component.canDeactivate()).resolves.toBe(true); await expect(component.canDeactivate()).resolves.toBe(true);
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25); expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(cartServiceStub.loadCart).toHaveBeenCalled(); expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(component.createdPurchaseId()).toBeNull(); expect(component.createdPurchaseId()).toBeNull();
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
});
it('prevents leaving checkout when the purchase cannot be cancelled', async () => {
checkoutServiceStub.cancelPurchase.mockRejectedValue({
error: { message: 'No se pudo cancelar la compra.' },
});
const { component } = createComponent();
await expect(component.canDeactivate()).resolves.toBe(false);
expect(toastServiceStub.danger).toHaveBeenCalledWith('No se pudo cancelar la compra.');
expect(component.createdPurchaseId()).toBe(25);
});
it('allows leaving checkout when cancellation finds an expired stock reservation', 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(
new HttpErrorResponse({
status: 422,
error: {
code: 'purchase.expired',
message: 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
},
}),
);
const { component } = createComponent();
await component.selectPaymentMethod('qr');
expect(toastServiceStub.danger).toHaveBeenCalledWith(
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
);
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
queryParams: { status: 'expired' },
});
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', () => {
const { component } = createComponent();
component.createdPurchase.set({
id: 25,
status: 'created',
expires_at: new Date(Date.now() - 1_000).toISOString(),
items: [],
subtotal: '100.00',
total: '100.00',
});
const handled = component.handleCheckoutError(
new HttpErrorResponse({
status: 422,
error: {
errors: {
purchase: ['La compra ya no se puede modificar.'],
},
},
}),
'No se pudieron actualizar los datos de la compra.',
);
expect(handled).toBe(true);
expect(toastServiceStub.danger).toHaveBeenCalledWith(
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
);
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
queryParams: { status: 'expired' },
});
}); });
}); });

View File

@@ -8,6 +8,7 @@ import {
signal, signal,
ViewChild, ViewChild,
} from '@angular/core'; } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms'; import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { firstValueFrom, startWith } from 'rxjs'; import { firstValueFrom, startWith } from 'rxjs';
@@ -19,13 +20,15 @@ import {
PurchaseDetailResponse, PurchaseDetailResponse,
} 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 { ToastService } from '../../../../core/services/toast.service';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
import { BankAccount } from '../../../../core/services/tenant.interface';
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component'; import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
import { StepComponent } from '../../../../shared/components/stepper/step.component'; import { StepComponent } from '../../../../shared/components/stepper/step.component';
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,
@@ -36,6 +39,12 @@ import {
TransferValidationStatus, TransferValidationStatus,
} from './checkout-page.models'; } from './checkout-page.models';
interface ApiErrorResponse {
code?: string;
message?: string;
errors?: Record<string, string[]>;
}
@Component({ @Component({
selector: 'app-checkout-page', selector: 'app-checkout-page',
standalone: true, standalone: true,
@@ -56,16 +65,25 @@ 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 toastService = inject(ToastService);
private readonly cartService = inject(CartService); private readonly cartService = inject(CartService);
private readonly qrPollingIntervalMs = 5_000; private readonly qrPollingIntervalMs = 5_000;
private readonly qrPollingMaxAttempts = 9; private readonly qrPollingMaxAttempts = 120;
private readonly transferPollingIntervalMs = 3_000;
private readonly transferPollingMaxAttempts = 209;
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null; private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
private qrPollingAttempts = 0; private qrPollingAttempts = 0;
private qrPollingRunId = 0; private qrPollingRunId = 0;
private transferPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
private transferPollingAttempts = 0;
private transferPollingRunId = 0;
private paymentMethodRequestId = 0; private paymentMethodRequestId = 0;
private navigationStarted = false; private navigationStarted = false;
private cancelPurchasePromise: Promise<boolean> | null = null;
@ViewChild(StepperComponent) stepper!: StepperComponent; @ViewChild(StepperComponent) stepper!: StepperComponent;
@@ -79,10 +97,28 @@ 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 cartEditingEnabled = computed( protected readonly checkoutRemainingTime = computed(() => {
() => this.tenantService.tenant()?.cart_editing_enabled ?? true, 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;
@@ -111,9 +147,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
protected readonly transferDni = signal<string>(''); protected readonly transferDni = signal<string>('');
protected readonly isUpdatingPurchase = signal(false); protected readonly isUpdatingPurchase = signal(false);
protected readonly isEditingItems = signal(false); protected readonly isCancellingPurchase = signal(false);
protected readonly isUpdatingItem = signal(false); protected readonly hasSubmittedTransfer = signal(false);
protected readonly isPreparingItemEdit = signal(false); protected readonly isPurchaseModificationDisabled = computed(
() => this.isCancellingPurchase() || this.hasSubmittedTransfer(),
);
protected readonly createdPurchaseId = signal<number | null>(null); protected readonly createdPurchaseId = signal<number | null>(null);
protected readonly isGeneratingIntent = signal(false); protected readonly isGeneratingIntent = signal(false);
protected readonly isPaymentLoading = computed(() => this.isGeneratingIntent()); protected readonly isPaymentLoading = computed(() => this.isGeneratingIntent());
@@ -147,7 +185,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
ngOnInit(): void { ngOnInit(): void {
const purchaseId = Number(this.route.snapshot.queryParamMap.get('purchase')); const purchaseId = Number(this.route.snapshot.paramMap.get('id'));
if (!Number.isInteger(purchaseId) || purchaseId <= 0) { if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
void this.router.navigate(['/']); void this.router.navigate(['/']);
return; return;
@@ -158,6 +196,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
ngOnDestroy(): void { ngOnDestroy(): void {
this.stopQrPolling(); this.stopQrPolling();
this.stopTransferPolling();
} }
private mapPurchaseItemToMock(item: PurchaseDetailItemResponse): CartItemMock { private mapPurchaseItemToMock(item: PurchaseDetailItemResponse): CartItemMock {
@@ -173,92 +212,30 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
value: attribute.value === null ? '' : String(attribute.value), value: attribute.value === null ? '' : String(attribute.value),
})), })),
quantity: item.quantity, quantity: item.quantity,
variantId: item.source_variant_id,
}; };
} }
protected async onEditingItemsChange(editing: boolean): Promise<void> { protected async onModifyPurchase(): Promise<void> {
if (this.isUpdatingItem() || this.isPreparingItemEdit()) { if (this.isPurchaseModificationDisabled()) {
return; return;
} }
if (editing && !this.cartEditingEnabled()) { this.globalLoadingService.start();
return;
}
if (!editing) {
this.isEditingItems.set(false);
if (this.stepper?.currentStepIndex() === 1) {
void this.selectPaymentMethod(this.selectedPaymentMethod());
}
return;
}
this.isEditingItems.set(true);
this.stopQrPolling();
this.qrData.set(null);
this.qrPaymentStatus.set('idle');
this.transferAccount.set(null);
this.transferValidationStatus.set('idle');
const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId();
if (!tenant || !purchaseId) {
this.isEditingItems.set(false);
return;
}
this.isPreparingItemEdit.set(true);
try { try {
const purchase = await this.checkoutService.prepareItemEditing(tenant.codigo, purchaseId); const cancelled = await this.cancelCurrentPurchase();
this.createdPurchase.set(purchase); if (!cancelled) return;
} catch (error) {
console.error('Failed to prepare purchase item editing:', error); await this.router.navigate(['/'], {
this.isEditingItems.set(false); queryParams: { openCart: true },
});
} finally { } finally {
this.isPreparingItemEdit.set(false); this.globalLoadingService.stop();
}
}
protected async onPurchaseItemQuantityChange(event: {
item: CartItemMock;
quantity: number;
}): Promise<void> {
const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId();
const itemId = event.item.cartItemId;
if (
!this.cartEditingEnabled() ||
!tenant ||
!purchaseId ||
!itemId ||
this.isUpdatingItem() ||
!this.isEditingItems()
) {
return;
}
this.isUpdatingItem.set(true);
try {
const purchase = await this.checkoutService.updateItemQuantity(
tenant.codigo,
purchaseId,
itemId,
event.quantity,
);
this.createdPurchase.set(purchase);
} catch (error) {
console.error('Failed to update purchase item quantity:', error);
} finally {
this.isUpdatingItem.set(false);
} }
} }
protected async onStep1Continue(): Promise<void> { protected async onStep1Continue(): Promise<void> {
if (this.form.invalid || this.isUpdatingPurchase() || this.isEditingItems()) return; if (this.form.invalid || this.isUpdatingPurchase()) return;
const tenant = this.tenantService.tenant(); const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId(); const purchaseId = this.createdPurchaseId();
@@ -275,6 +252,7 @@ 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();
@@ -282,56 +260,96 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
void this.selectPaymentMethod(this.selectedPaymentMethod()); void this.selectPaymentMethod(this.selectedPaymentMethod());
} catch (error) { } catch (error) {
console.error('Failed to create purchase:', error); console.error('Failed to create purchase:', error);
// Here we could show an alert or toast this.showRequestError(error, 'No se pudieron actualizar los datos de la compra.');
} finally { } finally {
this.isUpdatingPurchase.set(false); this.isUpdatingPurchase.set(false);
} }
} }
protected async onCancel(): Promise<void> { protected async onCancel(): Promise<void> {
if (await this.canDeactivate()) { void this.router.navigate(['/']);
void this.router.navigate(['/']);
}
} }
public async canDeactivate(): Promise<boolean> { public async canDeactivate(): Promise<boolean> {
this.stopQrPolling(); this.stopQrPolling();
this.stopTransferPolling();
if (this.cancelPurchasePromise) {
return this.cancelPurchasePromise;
}
if (this.navigationStarted) { if (this.navigationStarted) {
return true; return true;
} }
const purchaseId = this.createdPurchaseId(); this.globalLoadingService.start();
const tenant = this.tenantService.tenant(); try {
return await this.cancelCurrentPurchase();
} finally {
this.globalLoadingService.stop();
}
}
if (!purchaseId || !tenant) { private cancelCurrentPurchase(): Promise<boolean> {
if (this.cancelPurchasePromise) {
return this.cancelPurchasePromise;
}
this.cancelPurchasePromise = this.performPurchaseCancellation().finally(() => {
this.cancelPurchasePromise = null;
});
return this.cancelPurchasePromise;
}
private async performPurchaseCancellation(): Promise<boolean> {
const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId();
if (!tenant || !purchaseId) {
this.checkoutCountdownService.clear();
return true; return true;
} }
this.isCancellingPurchase.set(true);
try { try {
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId); await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
await firstValueFrom(this.cartService.loadCart());
this.createdPurchaseId.set(null); this.createdPurchaseId.set(null);
this.createdPurchase.set(null); this.createdPurchase.set(null);
this.checkoutCountdownService.clear();
try { this.navigationStarted = true;
await firstValueFrom(this.cartService.loadCart());
} catch (error) {
console.error('Failed to restore cart after cancelling checkout:', error);
}
return true; return true;
} catch (error) { } catch (error) {
console.error('Failed to cancel 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.');
return false; return false;
} finally {
this.isCancellingPurchase.set(false);
} }
} }
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> { protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
if (this.navigationStarted || this.isEditingItems()) { if (this.navigationStarted || this.hasSubmittedTransfer()) {
return; return;
} }
this.stopQrPolling(); this.stopQrPolling();
this.stopTransferPolling();
this.qrPaymentStatus.set('idle'); this.qrPaymentStatus.set('idle');
this.transferValidationStatus.set('idle'); this.transferValidationStatus.set('idle');
this.selectedPaymentMethod.set(method); this.selectedPaymentMethod.set(method);
@@ -371,13 +389,14 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
} catch (error) { } catch (error) {
console.error('Failed to generate payment intent:', error); console.error('Failed to generate payment intent:', error);
this.showRequestError(error, 'No se pudo generar el pago.');
} finally { } finally {
this.isGeneratingIntent.set(false); this.isGeneratingIntent.set(false);
} }
} }
protected async generateTransferIntent(dni: string): Promise<void> { protected async generateTransferIntent(dni: string): Promise<void> {
if (this.isEditingItems()) { if (this.hasSubmittedTransfer()) {
return; return;
} }
@@ -389,6 +408,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
this.transferDni.set(dni); this.transferDni.set(dni);
this.stopTransferPolling();
this.transferValidationStatus.set('idle'); this.transferValidationStatus.set('idle');
this.isGeneratingIntent.set(true); this.isGeneratingIntent.set(true);
try { try {
@@ -407,6 +427,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
} catch (error) { } catch (error) {
console.error('Failed to generate transfer payment intent:', error); console.error('Failed to generate transfer payment intent:', error);
this.showRequestError(error, 'No se pudo generar el pago por transferencia.');
} finally { } finally {
this.isGeneratingIntent.set(false); this.isGeneratingIntent.set(false);
} }
@@ -437,28 +458,116 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
!purchaseId || !purchaseId ||
!tenant || !tenant ||
this.navigationStarted || this.navigationStarted ||
this.isEditingItems() ||
this.transferValidationStatus() === 'checking' this.transferValidationStatus() === 'checking'
) { ) {
return; return;
} }
this.stopTransferPolling();
this.hasSubmittedTransfer.set(true);
this.transferValidationStatus.set('checking'); this.transferValidationStatus.set('checking');
this.transferPollingAttempts = 0;
const runId = this.transferPollingRunId;
try { try {
const purchase = await this.checkoutService const purchase = await this.checkoutService
.withCustomLoading() .withCustomLoading()
.getPurchase(tenant.codigo, purchaseId); .submitPurchaseForReview(tenant.codigo, purchaseId);
if (runId !== this.transferPollingRunId) {
return;
}
this.checkoutCountdownService.synchronize(purchase);
if (purchase.status === 'paid') { if (purchase.status === 'paid') {
this.navigateToPurchaseStatus(purchaseId); this.navigateToPurchaseStatus(purchaseId);
return; return;
} }
this.transferValidationStatus.set('error'); this.scheduleTransferPoll(runId);
} catch (error) {
const expired = this.handleCheckoutError(
error,
'No se pudo enviar el pago para su validación.',
);
if (!expired && runId === this.transferPollingRunId) {
this.transferValidationStatus.set('error');
}
}
}
private scheduleTransferPoll(runId: number): void {
this.transferPollingTimeoutId = setTimeout(() => {
this.transferPollingTimeoutId = null;
void this.checkTransferPayment(runId);
}, this.transferPollingIntervalMs);
}
private async checkTransferPayment(runId: number): Promise<void> {
if (runId !== this.transferPollingRunId) {
return;
}
const purchaseId = this.createdPurchaseId();
const tenant = this.tenantService.tenant();
if (!purchaseId || !tenant || this.selectedPaymentMethod() !== 'transfer') {
this.stopTransferPolling();
return;
}
this.transferPollingAttempts += 1;
try {
const purchase = await this.checkoutService
.withCustomLoading()
.getPurchase(tenant.codigo, purchaseId);
if (runId !== this.transferPollingRunId) {
return;
}
this.checkoutCountdownService.synchronize(purchase);
if (purchase.status === 'paid') {
this.navigateToPurchaseStatus(purchaseId);
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) {
return;
}
if (this.transferPollingAttempts >= this.transferPollingMaxAttempts) {
this.stopTransferPolling();
this.transferValidationStatus.set('error'); this.transferValidationStatus.set('error');
return;
}
this.scheduleTransferPoll(runId);
}
private stopTransferPolling(): void {
this.transferPollingRunId += 1;
if (this.transferPollingTimeoutId !== null) {
clearTimeout(this.transferPollingTimeoutId);
this.transferPollingTimeoutId = null;
} }
} }
@@ -509,6 +618,8 @@ 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;
@@ -519,8 +630,17 @@ 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);
@@ -572,6 +692,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.navigationStarted = true; this.navigationStarted = true;
this.stopQrPolling(); this.stopQrPolling();
this.stopTransferPolling();
this.checkoutCountdownService.clear();
void this.router.navigate(['/checkout/status', purchaseId]); void this.router.navigate(['/checkout/status', purchaseId]);
} }
@@ -583,6 +705,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return; return;
} }
this.createdPurchaseId.set(purchaseId);
try { try {
const purchase = await this.checkoutService const purchase = await this.checkoutService
.withCustomLoading() .withCustomLoading()
@@ -590,6 +714,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
if ( if (
(purchase.status === 'pending_payment' && purchase.expires_at === null) || (purchase.status === 'pending_payment' && purchase.expires_at === null) ||
purchase.status === 'in_review' ||
purchase.status === 'paid' || purchase.status === 'paid' ||
purchase.status === 'cancelled' || purchase.status === 'cancelled' ||
purchase.status === 'rejected' || purchase.status === 'rejected' ||
@@ -606,6 +731,7 @@ 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 (
@@ -623,7 +749,113 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
} catch (error) { } catch (error) {
console.error('Failed to load purchase:', error); console.error('Failed to load purchase:', error);
void this.router.navigate(['/']); const expired = this.showRequestError(error, 'No se pudo cargar la compra.');
if (!expired) {
void this.router.navigate(['/']);
}
} }
} }
private showRequestError(error: unknown, fallbackMessage: string): boolean {
const payload =
typeof error === 'object' && error !== null && 'error' in error
? (error as { error?: ApiErrorResponse }).error
: undefined;
const message =
typeof payload?.message === 'string' && payload.message.trim()
? payload.message
: fallbackMessage;
this.toastService.danger(message);
if (payload?.code === 'purchase.expired') {
this.navigateToExpiredPurchaseStatus();
return true;
}
return false;
}
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
if (!(error instanceof HttpErrorResponse)) {
this.toastService.danger(fallbackMessage);
return false;
}
const response = error.error as ApiErrorResponse | null;
if (response?.code === 'purchase.expired' || this.hasExpiredPurchase()) {
this.stopQrPolling();
this.stopTransferPolling();
this.toastService.danger(
response?.code === 'purchase.expired' && response.message
? response.message
: 'La compra venció. Iniciá una nueva compra.',
);
this.navigateToExpiredPurchaseStatus();
return true;
}
const validationMessage = response?.errors
? Object.values(response.errors).flat().find(Boolean)
: undefined;
this.toastService.danger(validationMessage ?? response?.message ?? fallbackMessage);
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 {
const purchase = this.createdPurchase();
if (!purchase) {
return false;
}
if (purchase.status === 'expired') {
return true;
}
if (!purchase.expires_at) {
return false;
}
return Date.parse(purchase.expires_at) <= Date.now();
}
} }

View File

@@ -7,13 +7,18 @@
<div class="payment-methods__list" role="radiogroup" aria-label="Metodo de pago"> <div class="payment-methods__list" role="radiogroup" aria-label="Metodo de pago">
@for (method of paymentMethods(); track method.id) { @for (method of paymentMethods(); track method.id) {
<label class="payment-method" [class.is-selected]="selectedPaymentMethod() === method.id"> <label
class="payment-method"
[class.is-selected]="selectedPaymentMethod() === method.id"
[class.is-disabled]="paymentMethodDisabled()"
>
<input <input
class="payment-method__radio" class="payment-method__radio"
type="radio" type="radio"
name="payment-method" name="payment-method"
[value]="method.id" [value]="method.id"
[checked]="selectedPaymentMethod() === method.id" [checked]="selectedPaymentMethod() === method.id"
[disabled]="paymentMethodDisabled()"
(change)="selectPaymentMethod(method.id)" (change)="selectPaymentMethod(method.id)"
/> />

View File

@@ -63,10 +63,14 @@
cursor: pointer; cursor: pointer;
transition: color 0.2s ease; transition: color 0.2s ease;
&:hover { &:not(.is-disabled):hover {
color: #4f4f4f; color: #4f4f4f;
} }
&.is-disabled {
cursor: default;
}
&.is-selected { &.is-selected {
color: var(--tenant-primary, #6376f3); color: var(--tenant-primary, #6376f3);
} }
@@ -79,6 +83,10 @@
cursor: pointer; cursor: pointer;
} }
&.is-disabled &__radio {
cursor: default;
}
&__label { &__label {
min-width: 0; min-width: 0;
font-size: 13px; font-size: 13px;
@@ -91,11 +99,13 @@
font-size: 0.95rem; font-size: 0.95rem;
opacity: 0; opacity: 0;
transform: translateX(-4px); transform: translateX(-4px);
transition: opacity 0.2s ease, transform 0.2s ease; transition:
opacity 0.2s ease,
transform 0.2s ease;
} }
&.is-selected &__chevron, &.is-selected &__chevron,
&:hover &__chevron { &:not(.is-disabled):hover &__chevron {
opacity: 1; opacity: 1;
transform: translateX(0); transform: translateX(0);
} }
@@ -140,6 +150,4 @@
font-weight: 700; font-weight: 700;
line-height: 1.35; line-height: 1.35;
} }
} }

View File

@@ -17,11 +17,12 @@ import {
imports: [CheckoutPaymentQrComponent, CheckoutPaymentTransferComponent], imports: [CheckoutPaymentQrComponent, CheckoutPaymentTransferComponent],
templateUrl: './checkout-payment-step.component.html', templateUrl: './checkout-payment-step.component.html',
styleUrl: './checkout-payment-step.component.scss', styleUrl: './checkout-payment-step.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class CheckoutPaymentStepComponent { export class CheckoutPaymentStepComponent {
readonly paymentMethods = input.required<ReadonlyArray<PaymentMethodOption>>(); readonly paymentMethods = input.required<ReadonlyArray<PaymentMethodOption>>();
readonly selectedPaymentMethod = input.required<PaymentMethod>(); readonly selectedPaymentMethod = input.required<PaymentMethod>();
readonly paymentMethodDisabled = input<boolean>(false);
readonly copiedTransferField = input<TransferField | null>(null); readonly copiedTransferField = input<TransferField | null>(null);
readonly transferAccount = input<TransferAccount | null>(null); readonly transferAccount = input<TransferAccount | null>(null);
readonly transferDni = input<string>(''); readonly transferDni = input<string>('');
@@ -40,6 +41,10 @@ export class CheckoutPaymentStepComponent {
readonly generateTransferIntent = output<string>(); readonly generateTransferIntent = output<string>();
protected selectPaymentMethod(method: PaymentMethod): void { protected selectPaymentMethod(method: PaymentMethod): void {
if (this.paymentMethodDisabled()) {
return;
}
this.paymentMethodChange.emit(method); this.paymentMethodChange.emit(method);
} }

View File

@@ -1,5 +1,6 @@
import { TestBed, getTestBed } from '@angular/core/testing'; import { TestBed, getTestBed } from '@angular/core/testing';
import { signal } from '@angular/core'; import { signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing'; import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
@@ -8,6 +9,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 { 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';
@@ -36,7 +38,7 @@ describe('ProductDetailPageComponent', () => {
has_tickets: false, has_tickets: false,
minimum_use_date: null, minimum_use_date: null,
maximum_use_date: null, maximum_use_date: null,
stock_tecnico: 10, maximum_addable_quantity: 10,
attributes: [], attributes: [],
variants: [], variants: [],
}; };
@@ -175,6 +177,21 @@ describe('ProductDetailPageComponent', () => {
expect(element.querySelector('.product-carousel__discount-badge')).toBeNull(); expect(element.querySelector('.product-carousel__discount-badge')).toBeNull();
}); });
it('reloads product availability when the cart changes', async () => {
catalogServiceStub.getCatalogItem.mockReturnValue(
of({ ...mockProduct, maximum_addable_quantity: 4 }),
);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges();
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
fixture.detectChanges();
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, undefined);
expect(fixture.componentInstance['selectedVariantMax']()).toBe(4);
});
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();
@@ -190,10 +207,10 @@ describe('ProductDetailPageComponent', () => {
const detailProduct: CatalogItemDetail = { const detailProduct: CatalogItemDetail = {
...mockProduct, ...mockProduct,
images: ['https://example.com/product.png'], images: ['https://example.com/product.png'],
variants: [{ id: 123, stock_tecnico: 10, values: {} }], variants: [{ id: 123, maximum_addable_quantity: 10, values: {} }],
selected_variant: { selected_variant: {
id: 123, id: 123,
stock_tecnico: 10, maximum_addable_quantity: 10,
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'], images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
values: {}, values: {},
}, },
@@ -294,10 +311,12 @@ describe('ProductDetailPageComponent', () => {
], ],
}, },
], ],
variants: [{ id: 123, stock_tecnico: 10, values: { color: 'beige', material: 'Cuero' } }], variants: [
{ id: 123, maximum_addable_quantity: 10, values: { color: 'beige', material: 'Cuero' } },
],
selected_variant: { selected_variant: {
id: 123, id: 123,
stock_tecnico: 10, maximum_addable_quantity: 10,
images: ['https://example.com/variant1.png'], images: ['https://example.com/variant1.png'],
values: { values: {
color: 'beige', color: 'beige',
@@ -334,8 +353,8 @@ describe('ProductDetailPageComponent', () => {
purpose: 'entry', purpose: 'entry',
has_tickets: true, has_tickets: true,
variants: [ variants: [
{ id: 101, event_date_id: 20, stock_tecnico: 10, values: { event_date: '20' } }, { id: 101, event_date_id: 20, maximum_addable_quantity: 10, values: { event_date: '20' } },
{ id: 102, event_date_id: 21, stock_tecnico: 10, values: { event_date: '21' } }, { id: 102, event_date_id: 21, maximum_addable_quantity: 10, values: { event_date: '21' } },
], ],
attributes: [ attributes: [
{ {
@@ -366,7 +385,7 @@ describe('ProductDetailPageComponent', () => {
selected_variant: { selected_variant: {
id: 101, id: 101,
event_date_id: 20, event_date_id: 20,
stock_tecnico: 10, maximum_addable_quantity: 10,
images: [], images: [],
values: {}, values: {},
}, },
@@ -410,7 +429,7 @@ describe('ProductDetailPageComponent', () => {
fixture.componentInstance['selectedVariant'].set({ fixture.componentInstance['selectedVariant'].set({
id: 1, id: 1,
stock_tecnico: 10, maximum_addable_quantity: 10,
values: {}, values: {},
}); });
fixture.detectChanges(); fixture.detectChanges();
@@ -488,9 +507,33 @@ describe('ProductDetailPageComponent', () => {
}, },
], ],
}); });
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout'], { expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout', 44]);
queryParams: { purchase: 44 }, });
});
it('shows the backend purchase-limit message for a direct checkout', async () => {
checkoutServiceStub.startCheckout.mockRejectedValue(
new HttpErrorResponse({
status: 422,
error: {
code: 'purchase.limit_exceeded',
message: 'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
maximum_addable_quantity: 2,
},
}),
);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges();
const buyButton = Array.from(
fixture.nativeElement.querySelectorAll('app-button button') as NodeListOf<HTMLButtonElement>,
).find((button) => button.textContent?.trim() === 'Comprar') as HTMLButtonElement;
buyButton.click();
await Promise.resolve();
expect(toastServiceStub.danger).toHaveBeenCalledWith(
'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
);
}); });
it('calls CartService.addItem when variant is selected and Add to Cart is clicked', async () => { it('calls CartService.addItem when variant is selected and Add to Cart is clicked', async () => {
@@ -499,13 +542,13 @@ describe('ProductDetailPageComponent', () => {
variants: [ variants: [
{ {
id: 123, id: 123,
stock_tecnico: 5, maximum_addable_quantity: 5,
values: {}, values: {},
}, },
], ],
selected_variant: { selected_variant: {
id: 123, id: 123,
stock_tecnico: 5, maximum_addable_quantity: 5,
images: [], images: [],
values: {}, values: {},
}, },
@@ -538,7 +581,7 @@ describe('ProductDetailPageComponent', () => {
resolveProduct({ resolveProduct({
...mockProduct, ...mockProduct,
variants: [], variants: [],
stock_tecnico: 4, maximum_addable_quantity: 4,
}); });
await configureTestingModule(); await configureTestingModule();
@@ -564,13 +607,13 @@ describe('ProductDetailPageComponent', () => {
variants: [ variants: [
{ {
id: 123, id: 123,
stock_tecnico: 5, maximum_addable_quantity: 5,
values: {}, values: {},
}, },
], ],
selected_variant: { selected_variant: {
id: 123, id: 123,
stock_tecnico: 5, maximum_addable_quantity: 5,
images: [], images: [],
values: {}, values: {},
}, },
@@ -602,7 +645,7 @@ describe('ProductDetailPageComponent', () => {
it('allows unlimited variants to increase quantity without a maximum', async () => { it('allows unlimited variants to increase quantity without a maximum', async () => {
const unlimitedVariant = { const unlimitedVariant = {
id: 321, id: 321,
stock_tecnico: null, maximum_addable_quantity: null,
values: {}, values: {},
}; };
resolveProduct({ resolveProduct({
@@ -610,7 +653,7 @@ describe('ProductDetailPageComponent', () => {
inventory_policy: 'unlimited', inventory_policy: 'unlimited',
selected_variant: { selected_variant: {
id: 321, id: 321,
stock_tecnico: null, maximum_addable_quantity: null,
images: [], images: [],
values: {}, values: {},
}, },
@@ -634,7 +677,7 @@ describe('ProductDetailPageComponent', () => {
it('caps an unlimited variant at the per-user purchase limit', async () => { it('caps an unlimited variant at the per-user purchase limit', async () => {
const unlimitedVariant = { const unlimitedVariant = {
id: 322, id: 322,
stock_tecnico: null, maximum_addable_quantity: 2,
values: {}, values: {},
}; };
resolveProduct({ resolveProduct({
@@ -643,7 +686,7 @@ describe('ProductDetailPageComponent', () => {
max_units_per_user: 2, max_units_per_user: 2,
selected_variant: { selected_variant: {
id: 322, id: 322,
stock_tecnico: null, maximum_addable_quantity: 2,
images: [], images: [],
values: { event_date: '20' }, values: { event_date: '20' },
}, },
@@ -667,14 +710,14 @@ describe('ProductDetailPageComponent', () => {
it('disables purchase actions for tracked variants without stock', async () => { it('disables purchase actions for tracked variants without stock', async () => {
const trackedVariant = { const trackedVariant = {
id: 654, id: 654,
stock_tecnico: 0, maximum_addable_quantity: 0,
values: {}, values: {},
}; };
resolveProduct({ resolveProduct({
...mockProduct, ...mockProduct,
selected_variant: { selected_variant: {
id: 654, id: 654,
stock_tecnico: 0, maximum_addable_quantity: 0,
images: [], images: [],
values: {}, values: {},
}, },

View File

@@ -17,6 +17,7 @@ import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
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 { 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 { import {
@@ -51,6 +52,7 @@ export class ProductDetailPageComponent 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 catalogService = inject(CatalogService); private readonly catalogService = inject(CatalogService);
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
private readonly toastService = inject(ToastService); private readonly toastService = inject(ToastService);
private readonly cartService = inject(CartService); private readonly cartService = inject(CartService);
private readonly checkoutService = inject(CheckoutService); private readonly checkoutService = inject(CheckoutService);
@@ -64,6 +66,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
private routeSub: Subscription | null = null; private routeSub: Subscription | null = null;
private productSub: Subscription | null = null; private productSub: Subscription | null = null;
private availabilityChangedSub: Subscription | null = null;
private carouselResizeObserver: ResizeObserver | null = null; private carouselResizeObserver: ResizeObserver | null = null;
private observedCarouselPreview: HTMLElement | null = null; private observedCarouselPreview: HTMLElement | null = null;
private measurementTimer: ReturnType<typeof setTimeout> | null = null; private measurementTimer: ReturnType<typeof setTimeout> | null = null;
@@ -98,27 +101,23 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
const variant = this.selectedVariant(); const variant = this.selectedVariant();
if (!prod) return 0; if (!prod) return 0;
const stockLimit = variant return variant
? variant.stock_tecnico ? (variant.maximum_addable_quantity ?? null)
: prod.variants.length === 0 : prod.variants.length === 0
? (prod.stock_tecnico ?? null) ? (prod.maximum_addable_quantity ?? null)
: 0; : 0;
const userLimit = prod.max_units_per_user ?? null;
if (stockLimit === null) return userLimit;
if (userLimit === null) return stockLimit;
return Math.min(stockLimit, userLimit);
}); });
protected readonly selectedVariantAvailable = computed(() => { protected readonly selectedVariantAvailable = computed(() => {
const prod = this.product(); const prod = this.product();
if (!prod) return false; if (!prod) return false;
if (this.selectedVariantMax() === 0) return false;
const variant = this.selectedVariant(); const variant = this.selectedVariant();
if (variant) return this.isVariantAvailable(variant, prod); if (variant) return this.isVariantAvailable(variant);
if (prod.purpose === 'entry') return false; if (prod.purpose === 'entry') return false;
if (prod.variants.length > 0) return false; if (prod.variants.length > 0) return false;
return prod.inventory_policy === 'unlimited' || (prod.stock_tecnico ?? 0) > 0; return this.selectedVariantMax() !== 0;
}); });
protected readonly descriptionExpanded = signal(false); protected readonly descriptionExpanded = signal(false);
protected readonly descriptionMaxHeight = signal(0); protected readonly descriptionMaxHeight = signal(0);
@@ -154,6 +153,10 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
} }
ngOnInit(): void { ngOnInit(): void {
this.availabilityChangedSub = this.catalogAvailabilityService.availabilityChanged$.subscribe(
() => this.refreshProductAvailability(),
);
this.routeSub = this.route.data.subscribe((data) => { this.routeSub = this.route.data.subscribe((data) => {
const resolvedData = data['productDetailData'] as ProductDetailResolvedData | undefined; const resolvedData = data['productDetailData'] as ProductDetailResolvedData | undefined;
@@ -164,6 +167,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.availabilityChangedSub?.unsubscribe();
this.routeSub?.unsubscribe(); this.routeSub?.unsubscribe();
this.productSub?.unsubscribe(); this.productSub?.unsubscribe();
this.carouselResizeObserver?.disconnect(); this.carouselResizeObserver?.disconnect();
@@ -200,6 +204,32 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
}); });
} }
private refreshProductAvailability(): void {
const currentProduct = this.product();
if (!currentProduct) {
return;
}
const variantId = this.selectedVariant()?.id;
this.productSub?.unsubscribe();
this.productSub = this.catalogService
.withCustomLoading()
.getCatalogItem(currentProduct.id, variantId)
.subscribe({
next: (product) => {
this.applyProduct(product, false);
const maximum = this.selectedVariantMax();
if (maximum !== null && this.quantity() > maximum) {
this.quantity.set(Math.max(1, maximum));
}
},
error: () => {
// Keep the last known availability if the silent refresh fails.
},
});
}
private applyResolvedData(resolvedData: ProductDetailResolvedData): void { private applyResolvedData(resolvedData: ProductDetailResolvedData): void {
this.productSub?.unsubscribe(); this.productSub?.unsubscribe();
this.loading.set(false); this.loading.set(false);
@@ -328,19 +358,21 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
], ],
}); });
await this.router.navigate(['/checkout'], { await this.router.navigate(['/checkout', purchase.id]);
queryParams: { purchase: purchase.id },
});
} catch (error) { } catch (error) {
console.error('Failed to create direct purchase:', error); console.error('Failed to create direct purchase:', error);
this.toastService.danger('No se pudo iniciar la compra directa.'); const message =
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
? error.error.message
: 'No se pudo iniciar la compra directa.';
this.toastService.danger(message);
} finally { } finally {
this.creatingDirectPurchase.set(false); this.creatingDirectPurchase.set(false);
} }
} }
private isVariantAvailable(variant: CatalogItemVariant, product: CatalogItemDetail): boolean { private isVariantAvailable(variant: CatalogItemVariant): boolean {
return product.inventory_policy === 'unlimited' || (variant.stock_tecnico ?? 0) > 0; return variant.maximum_addable_quantity !== 0;
} }
protected toggleDescription(): void { protected toggleDescription(): void {

View File

@@ -15,6 +15,7 @@ import {
describe('productDetailResolver', () => { describe('productDetailResolver', () => {
const product: CatalogItemDetail = { const product: CatalogItemDetail = {
id: 1, id: 1,
type: 'product',
category_id: 10, category_id: 10,
brand_id: null, brand_id: null,
slug: 'auriculares-bluetooth', slug: 'auriculares-bluetooth',
@@ -28,7 +29,7 @@ describe('productDetailResolver', () => {
has_tickets: false, has_tickets: false,
minimum_use_date: null, minimum_use_date: null,
maximum_use_date: null, maximum_use_date: null,
stock_tecnico: 0, maximum_addable_quantity: 0,
attributes: [], attributes: [],
variants: [], variants: [],
}; };

View File

@@ -5,6 +5,7 @@ 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';
@@ -66,7 +67,7 @@ describe('PurchaseStatusPageComponent', () => {
TestBed.resetTestingModule(); TestBed.resetTestingModule();
}); });
async function render(hasGeneratedTickets: boolean) { async function render(hasGeneratedTickets: boolean, forcedStatus?: string) {
const checkoutService = { const checkoutService = {
getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)), getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)),
withCustomLoading() { withCustomLoading() {
@@ -77,15 +78,24 @@ 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: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } }, useValue: {
snapshot: {
paramMap: convertToParamMap({ id: '42' }),
queryParamMap: convertToParamMap(
forcedStatus ? { status: forcedStatus } : {},
),
},
},
}, },
{ provide: Router, useValue: router }, { provide: Router, useValue: router },
], ],
@@ -100,15 +110,22 @@ 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('Ver mis tickets'); expect(element.textContent).toContain('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();
@@ -134,6 +151,14 @@ 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('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();
@@ -147,11 +172,13 @@ 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,
@@ -174,6 +201,7 @@ 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);
@@ -197,6 +225,7 @@ 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,

View File

@@ -15,6 +15,7 @@ import {
CheckoutService, CheckoutService,
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';
@@ -35,6 +36,7 @@ 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));
@@ -72,6 +74,12 @@ 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();
} }
@@ -98,6 +106,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
this.status.set(status); this.status.set(status);
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true); this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
if (status === 'approved') {
this.cartService.clearCart();
}
if (status === 'pending') { if (status === 'pending') {
this.schedulePolling(); this.schedulePolling();
} else { } else {
@@ -107,7 +119,10 @@ 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 (isPolling) { if (this.isPurchaseExpiredError(error)) {
this.status.set('expired');
this.stopPolling();
} else if (isPolling) {
this.schedulePolling(); this.schedulePolling();
} else { } else {
this.status.set('error'); this.status.set('error');
@@ -154,6 +169,14 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
return 'pending'; return 'pending';
} }
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();

View File

@@ -38,11 +38,13 @@
<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" type="password-toggle"
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>
@@ -51,11 +53,13 @@
<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" type="password-toggle"
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>

View File

@@ -12,6 +12,48 @@ 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(

View File

@@ -48,6 +48,7 @@ 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)]],
@@ -67,6 +68,11 @@ 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']);

View File

@@ -13,11 +13,13 @@
<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" type="password-toggle"
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>
@@ -30,11 +32,13 @@
</label> </label>
<app-input <app-input
id="reset-password-confirmation" id="reset-password-confirmation"
type="password" type="password-toggle"
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>

View File

@@ -50,6 +50,43 @@ 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(),

View File

@@ -49,6 +49,7 @@ 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') ?? '';
@@ -72,6 +73,11 @@ 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));

View File

@@ -7,6 +7,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
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 { 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';
@@ -108,6 +109,16 @@ describe('SearchPageComponent', () => {
); );
}); });
it('repeats the current search when catalog availability changes', () => {
const fixture = TestBed.createComponent(SearchPageComponent);
fixture.detectChanges();
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
expect(searchCatalog).toHaveBeenCalledTimes(2);
expect(searchCatalog).toHaveBeenLastCalledWith({ q: 'running', page: 1 });
});
it('renders the search title and query subtitle with the category header layout', () => { it('renders the search title and query subtitle with the category header layout', () => {
const fixture = TestBed.createComponent(SearchPageComponent); const fixture = TestBed.createComponent(SearchPageComponent);
fixture.detectChanges(); fixture.detectChanges();

View File

@@ -9,12 +9,25 @@ import {
signal, signal,
} from '@angular/core'; } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { catchError, distinctUntilChanged, finalize, map, of, switchMap, tap } from 'rxjs'; import {
catchError,
combineLatest,
distinctUntilChanged,
finalize,
map,
of,
startWith,
switchMap,
tap,
} from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { CheckoutService } from '../../../../core/services/checkout.service'; import {
CheckoutService,
isExpiredStockReservationResponse,
} from '../../../../core/services/checkout.service';
import { import {
CatalogFeaturedItem, CatalogFeaturedItem,
CatalogFeaturedItems, CatalogFeaturedItems,
@@ -22,6 +35,7 @@ import {
CatalogProductLayout, CatalogProductLayout,
} 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 { ApiPaginatedResponse } from '../../../../core/services/api-paginated-response.interface'; import { ApiPaginatedResponse } from '../../../../core/services/api-paginated-response.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';
@@ -46,6 +60,7 @@ interface SearchRouteState {
export class SearchPageComponent { export class SearchPageComponent {
private readonly minSearchLength = 3; private readonly minSearchLength = 3;
private readonly cartService = inject(CartService); private readonly cartService = inject(CartService);
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
private readonly catalogService = inject(CatalogService); private readonly catalogService = inject(CatalogService);
private readonly injector = inject(Injector); private readonly injector = inject(Injector);
private readonly destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
@@ -86,26 +101,33 @@ export class SearchPageComponent {
}); });
constructor() { constructor() {
this.route.queryParamMap const routeState$ = this.route.queryParamMap.pipe(
.pipe( map(
map( (params): SearchRouteState => ({
(params): SearchRouteState => ({ query: params.get('q')?.trim() ?? '',
query: params.get('q')?.trim() ?? '', page: this.parsePage(params.get('page')),
page: this.parsePage(params.get('page')),
}),
),
distinctUntilChanged(
(previous, current) => previous.query === current.query && previous.page === current.page,
),
tap(({ query }) => {
this.query.set(query);
this.results.set(null);
this.error.set(
query.length >= this.minSearchLength
? null
: `Ingresá al menos ${this.minSearchLength} caracteres para buscar.`,
);
}), }),
),
distinctUntilChanged(
(previous, current) => previous.query === current.query && previous.page === current.page,
),
tap(({ query }) => {
this.query.set(query);
this.results.set(null);
this.error.set(
query.length >= this.minSearchLength
? null
: `Ingresá al menos ${this.minSearchLength} caracteres para buscar.`,
);
}),
);
combineLatest([
routeState$,
this.catalogAvailabilityService.availabilityChanged$.pipe(startWith(undefined)),
])
.pipe(
map(([routeState]) => routeState),
switchMap(({ query, page }) => { switchMap(({ query, page }) => {
if (query.length < this.minSearchLength) { if (query.length < this.minSearchLength) {
return of(null); return of(null);
@@ -180,10 +202,20 @@ export class SearchPageComponent {
], ],
}, },
); );
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } }); await this.router.navigate(['/checkout', purchase.id]);
} catch (error) { } catch (error) {
console.error('Failed to create direct purchase:', error); console.error('Failed to create direct purchase:', error);
this.toastService.danger('No se pudo iniciar la compra directa.'); const message =
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
? error.error.message
: 'No se pudo iniciar la compra directa.';
this.toastService.danger(message);
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);
} }

View File

@@ -23,7 +23,7 @@
</p> </p>
} @else { } @else {
@for (group of catalog(); track group.id) { @for (group of catalog(); track group.id) {
<app-store-section [title]="group.title"> <app-store-section [attr.id]="group.code" [title]="group.title">
<app-product-list <app-product-list
[layout]="group.layout" [layout]="group.layout"
[groupLayout]="group.group_layout" [groupLayout]="group.group_layout"

View File

@@ -11,6 +11,10 @@ app-store-section + app-store-section {
margin-top: clamp(3rem, 6vw, 5rem); margin-top: clamp(3rem, 6vw, 5rem);
} }
app-store-section[id] {
scroll-margin-top: 8rem;
}
:host > .store-home__additional-info:not(:first-child) { :host > .store-home__additional-info:not(:first-child) {
margin-top: clamp(3rem, 6vw, 5rem); margin-top: clamp(3rem, 6vw, 5rem);
} }

View File

@@ -12,6 +12,7 @@ import {
CatalogFeaturedItem, CatalogFeaturedItem,
} 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 { 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';
@@ -58,6 +59,7 @@ function createCatalog(
return [ return [
{ {
id: 7, id: 7,
code: 'destacados',
title: 'Destacados', title: 'Destacados',
layout: 'column_with_image', layout: 'column_with_image',
group_layout: 'paginated', group_layout: 'paginated',
@@ -77,12 +79,14 @@ function provideActivatedRoute(catalogData: StoreHomeCatalogResolvedData) {
const pageOneItems: CatalogFeaturedItem[] = [ const pageOneItems: CatalogFeaturedItem[] = [
{ {
id: 1, id: 1,
type: 'product',
nombre: 'Auriculares Bluetooth', nombre: 'Auriculares Bluetooth',
precio: '24999.00', precio: '24999.00',
image: '/catalog/auriculares.jpg', image: '/catalog/auriculares.jpg',
}, },
{ {
id: 2, id: 2,
type: 'product',
nombre: 'Teclado Mecanico', nombre: 'Teclado Mecanico',
precio: '18999.00', precio: '18999.00',
image: null, image: null,
@@ -149,6 +153,7 @@ describe('StoreHomePageComponent', () => {
const element = fixture.nativeElement as HTMLElement; const element = fixture.nativeElement as HTMLElement;
expect(catalogServiceStub.getCatalog).not.toHaveBeenCalled(); expect(catalogServiceStub.getCatalog).not.toHaveBeenCalled();
expect(element.querySelector('app-store-section')?.id).toBe('destacados');
expect(element.querySelector('.store-section__title')?.textContent?.trim()).toBe('Destacados'); expect(element.querySelector('.store-section__title')?.textContent?.trim()).toBe('Destacados');
expect(element.querySelectorAll('app-product-column-with-image')).toHaveLength(2); expect(element.querySelectorAll('app-product-column-with-image')).toHaveLength(2);
expect(element.textContent).toContain('Auriculares Bluetooth'); expect(element.textContent).toContain('Auriculares Bluetooth');
@@ -157,6 +162,30 @@ describe('StoreHomePageComponent', () => {
); );
}); });
it('reloads the catalog when availability changes', async () => {
const refreshedCatalog = createCatalog();
const catalogServiceStub = {
getCatalog: vi.fn().mockReturnValue(of(refreshedCatalog)),
getFeaturedGroupItems: vi.fn(),
withCustomLoading: vi.fn(),
};
catalogServiceStub.withCustomLoading.mockReturnValue(catalogServiceStub);
await TestBed.configureTestingModule({
imports: [StoreHomePageComponent],
providers: [
provideActivatedRoute({ response: createCatalog(), error: null }),
{ provide: CatalogService, useValue: catalogServiceStub },
],
}).compileComponents();
const fixture = TestBed.createComponent(StoreHomePageComponent);
fixture.detectChanges();
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
expect(catalogServiceStub.getCatalog).toHaveBeenCalledOnce();
});
it('renders the carousel URLs received in tenant extras', async () => { it('renders the carousel URLs received in tenant extras', async () => {
const carousel = ['https://example.com/carousel-1.webp', 'https://example.com/carousel-2.webp']; const carousel = ['https://example.com/carousel-1.webp', 'https://example.com/carousel-2.webp'];
@@ -376,7 +405,9 @@ describe('StoreHomePageComponent', () => {
}); });
it('requests another page for the selected featured group', async () => { it('requests another page for the selected featured group', async () => {
const pageTwoItems = [{ id: 3, nombre: 'Mouse Gamer', precio: '15999.00', image: null }]; const pageTwoItems: CatalogFeaturedItem[] = [
{ id: 3, type: 'product', nombre: 'Mouse Gamer', precio: '15999.00', image: null },
];
const catalogServiceStub = { const catalogServiceStub = {
getCatalog: vi.fn(), getCatalog: vi.fn(),
getFeaturedGroupItems: vi.fn().mockReturnValue(of(createItemsPage(pageTwoItems, 2, 2))), getFeaturedGroupItems: vi.fn().mockReturnValue(of(createItemsPage(pageTwoItems, 2, 2))),

View File

@@ -15,11 +15,13 @@ import { finalize, Subscription } from 'rxjs';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { CatalogFeaturedGroup } from '../../../../core/services/catalog/catalog.interface'; import { CatalogFeaturedGroup } from '../../../../core/services/catalog/catalog.interface';
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
import { CatalogService } from '../../../../core/services/catalog/catalog.service'; import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service'; import { 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 {
@@ -49,6 +51,7 @@ import {
}) })
export class StoreHomePageComponent implements OnInit, OnDestroy { export class StoreHomePageComponent implements OnInit, OnDestroy {
private readonly cartService = inject(CartService); private readonly cartService = inject(CartService);
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
private readonly catalogService = inject(CatalogService); private readonly catalogService = inject(CatalogService);
private readonly injector = inject(Injector); private readonly injector = inject(Injector);
private readonly route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
@@ -96,9 +99,13 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
protected readonly hasMainCarouselImages = computed(() => this.mainCarouselImages().length > 0); protected readonly hasMainCarouselImages = computed(() => this.mainCarouselImages().length > 0);
private catalogRequestSubscription: Subscription | null = null; private catalogRequestSubscription: Subscription | null = null;
private availabilityChangedSubscription: Subscription | null = null;
private readonly groupRequestSubscriptions = new Map<number, Subscription>(); private readonly groupRequestSubscriptions = new Map<number, Subscription>();
ngOnInit(): void { ngOnInit(): void {
this.availabilityChangedSubscription =
this.catalogAvailabilityService.availabilityChanged$.subscribe(() => this.loadCatalog(true));
const resolvedData = this.route.snapshot.data['catalogData'] as const resolvedData = this.route.snapshot.data['catalogData'] as
| StoreHomeCatalogResolvedData | StoreHomeCatalogResolvedData
| undefined; | undefined;
@@ -112,6 +119,7 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.availabilityChangedSubscription?.unsubscribe();
this.catalogRequestSubscription?.unsubscribe(); this.catalogRequestSubscription?.unsubscribe();
this.groupRequestSubscriptions.forEach((subscription) => subscription.unsubscribe()); this.groupRequestSubscriptions.forEach((subscription) => subscription.unsubscribe());
} }
@@ -210,10 +218,18 @@ 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'], { queryParams: { purchase: purchase.id } }); await this.router.navigate(['/checkout', 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)
@@ -224,6 +240,11 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
return; return;
} }
if (error instanceof HttpErrorResponse && typeof error.error?.message === 'string') {
this.toastService.danger(error.error.message);
return;
}
this.toastService.danger('No se pudo iniciar la compra directa.'); this.toastService.danger('No se pudo iniciar la compra directa.');
} finally { } finally {
this.creatingDirectPurchase.set(false); this.creatingDirectPurchase.set(false);
@@ -259,20 +280,27 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
}); });
} }
private loadCatalog(): void { private loadCatalog(silent = false): void {
this.loading.set(true); if (!silent) {
this.error.set(null); this.loading.set(true);
this.error.set(null);
}
this.catalogRequestSubscription?.unsubscribe(); this.catalogRequestSubscription?.unsubscribe();
this.catalogRequestSubscription = this.catalogService this.catalogRequestSubscription = this.catalogService
.withCustomLoading() .withCustomLoading()
.getCatalog() .getCatalog()
.subscribe({ .subscribe({
next: (catalog) => this.catalog.set(catalog), next: (catalog) => {
this.catalog.set(catalog);
this.error.set(null);
},
error: () => { error: () => {
this.catalog.set([]); if (!silent) {
this.catalog.set([]);
this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE);
}
this.loading.set(false); this.loading.set(false);
this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE);
}, },
complete: () => this.loading.set(false), complete: () => this.loading.set(false),
}); });

View File

@@ -91,15 +91,6 @@ export const routes: Routes = [
(m) => m.ProductDetailPageComponent, (m) => m.ProductDetailPageComponent,
), ),
}, },
{
path: 'checkout',
canActivate: [authGuard, hasMenuGuard('checkout')],
canDeactivate: [checkoutPendingPurchaseGuard],
loadComponent: () =>
import('./pages/checkout-page/checkout-page.component').then(
(m) => m.CheckoutPageComponent,
),
},
{ {
path: 'checkout/status', path: 'checkout/status',
component: SimpleLayoutComponent, component: SimpleLayoutComponent,
@@ -113,6 +104,15 @@ export const routes: Routes = [
}, },
], ],
}, },
{
path: 'checkout/:id',
canActivate: [authGuard, hasMenuGuard('checkout')],
canDeactivate: [checkoutPendingPurchaseGuard],
loadComponent: () =>
import('./pages/checkout-page/checkout-page.component').then(
(m) => m.CheckoutPageComponent,
),
},
{ {
path: 'ayuda', path: 'ayuda',
canActivate: [hasMenuGuard('help')], canActivate: [hasMenuGuard('help')],

View File

@@ -1,7 +1,9 @@
<button <button
type="button" type="button"
[disabled]="disabled()" [disabled]="disabled()"
[class.cart-icon--disabled]="disabled()"
[attr.aria-label]="ariaLabel()" [attr.aria-label]="ariaLabel()"
[attr.aria-disabled]="disabled()"
class="cart-icon" class="cart-icon"
> >
<div class="cart-icon__container"> <div class="cart-icon__container">

View File

@@ -14,7 +14,9 @@
color: #666666; color: #666666;
cursor: pointer; cursor: pointer;
outline: none; outline: none;
transition: color 0.15s ease-in-out, transform 0.1s ease-in-out; transition:
color 0.15s ease-in-out,
transform 0.1s ease-in-out;
border-radius: 4px; border-radius: 4px;
// Active state subtle scale down // Active state subtle scale down
@@ -29,10 +31,12 @@
} }
// Disabled state // Disabled state
&:disabled { &:disabled,
color: #A0A0A0; &.cart-icon--disabled {
color: #b8b8b8;
cursor: not-allowed; cursor: not-allowed;
pointer-events: none; pointer-events: none;
opacity: 0.45;
} }
} }
@@ -59,6 +63,11 @@
line-height: 1; line-height: 1;
} }
.cart-icon:disabled .cart-icon__glyph,
.cart-icon--disabled .cart-icon__glyph {
color: #b8b8b8;
}
.cart-icon__badge { .cart-icon__badge {
position: absolute; position: absolute;
top: -8px; top: -8px;

View File

@@ -6,7 +6,7 @@ import { CartIconComponent } from './cart-icon.component';
describe('CartIconComponent', () => { describe('CartIconComponent', () => {
beforeEach(async () => { beforeEach(async () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [CartIconComponent] imports: [CartIconComponent],
}).compileComponents(); }).compileComponents();
}); });
@@ -20,7 +20,7 @@ describe('CartIconComponent', () => {
return { return {
fixture, fixture,
element: fixture.nativeElement as HTMLElement element: fixture.nativeElement as HTMLElement,
}; };
} }
@@ -47,9 +47,11 @@ describe('CartIconComponent', () => {
}); });
it('disables the button when disabled is true', () => { it('disables the button when disabled is true', () => {
const { element } = setup(undefined, true); const { element } = setup(3, true);
const button = element.querySelector('button'); const button = element.querySelector('button');
expect(button?.disabled).toBe(true); expect(button?.disabled).toBe(true);
expect(button?.classList).toContain('cart-icon--disabled');
expect(element.querySelector('[data-testid="cart-badge"]')).toBeNull();
}); });
it('enables the button when disabled is false', () => { it('enables the button when disabled is false', () => {

View File

@@ -5,7 +5,7 @@ import { ChangeDetectionStrategy, Component, computed, input } from '@angular/co
imports: [], imports: [],
templateUrl: './cart-icon.component.html', templateUrl: './cart-icon.component.html',
styleUrl: './cart-icon.component.scss', styleUrl: './cart-icon.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class CartIconComponent { export class CartIconComponent {
readonly quantity = input<number | null | undefined>(undefined); readonly quantity = input<number | null | undefined>(undefined);
@@ -13,6 +13,10 @@ export class CartIconComponent {
readonly ariaLabel = input<string>('Carrito de compras'); readonly ariaLabel = input<string>('Carrito de compras');
protected readonly hasQuantity = computed(() => { protected readonly hasQuantity = computed(() => {
if (this.disabled()) {
return false;
}
const q = this.quantity(); const q = this.quantity();
return q !== null && q !== undefined && q > 0; return q !== null && q !== undefined && q > 0;
}); });

View File

@@ -26,7 +26,7 @@
</div> </div>
</div> </div>
@if (hasVariantSelectors() && !quantityDisabled()) { @if (hasVariantSelectors() && !variantDisabled()) {
<app-variant-selector <app-variant-selector
class="cart-item-variant-selector" class="cart-item-variant-selector"
[variants]="variants()" [variants]="variants()"
@@ -55,7 +55,7 @@
(increase)="onIncrease()" (increase)="onIncrease()"
(decrease)="onDecrease()" (decrease)="onDecrease()"
/> />
@if (!quantityDisabled() && showRemove()) { @if (!removeDisabled() && allowDelete()) {
<app-icon-button variant="trash" class="cart-item-remove-btn" (click)="onRemove()" /> <app-icon-button variant="trash" class="cart-item-remove-btn" (click)="onRemove()" />
} }
</div> </div>

View File

@@ -31,7 +31,9 @@ export class CartItemComponent {
readonly quantity = input<number>(1); readonly quantity = input<number>(1);
readonly readonly = input<boolean>(false); readonly readonly = input<boolean>(false);
readonly quantityDisabled = input<boolean>(false); readonly quantityDisabled = input<boolean>(false);
readonly showRemove = input<boolean>(true); readonly variantDisabled = input<boolean>(false);
readonly removeDisabled = input<boolean>(false);
readonly allowDelete = input<boolean>(true);
readonly quantityChange = output<number>(); readonly quantityChange = output<number>();
readonly remove = output<void>(); readonly remove = output<void>();
@@ -61,7 +63,7 @@ export class CartItemComponent {
} }
protected onVariantChange(variant: unknown): void { protected onVariantChange(variant: unknown): void {
if (!this.quantityDisabled() && typeof variant === 'number') { if (!this.variantDisabled() && typeof variant === 'number') {
this.variantChange.emit(variant); this.variantChange.emit(variant);
} }
} }

View File

@@ -1,20 +1,25 @@
<section <section
class="d-flex flex-column h-100 overflow-hidden text-secondary" class="d-flex flex-column overflow-hidden text-secondary cart-shell"
[style.background-color]="backgroundColor()" [style.background-color]="backgroundColor()"
> >
<header class="d-flex align-items-center p-3 justify-content-between bg-transparent cart-header"> <header class="d-flex align-items-center p-3 justify-content-between bg-transparent cart-header">
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2> <h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
<div class="d-flex align-items-center cart-header-actions"> <div class="d-flex align-items-center cart-header-actions">
@if (!readonly() && editable() && allowEditing() && items().length > 0) { @if (
allowModify() &&
(!readonly() || showModifyWhenReadonly()) &&
(requireEditingMode() || modifyAsAction()) &&
items().length > 0
) {
<button <button
class="btn btn-link p-0 border-0 cart-edit-btn" class="btn btn-link p-0 border-0 cart-edit-btn"
type="button" type="button"
[attr.aria-pressed]="editing()" [attr.aria-pressed]="modifyAsAction() ? null : editing()"
[disabled]="editingDisabled()" [disabled]="editingDisabled()"
(click)="toggleEditing()" (click)="toggleEditing()"
> >
{{ editing() ? 'Listo' : 'Modificar' }} {{ !modifyAsAction() && editing() ? 'Listo' : 'Modificar' }}
</button> </button>
} }
@@ -48,8 +53,22 @@
[selectedVariant]="getItemVariant(item)" [selectedVariant]="getItemVariant(item)"
[quantity]="getItemQuantity(item)" [quantity]="getItemQuantity(item)"
[readonly]="readonly()" [readonly]="readonly()"
[quantityDisabled]="!editable() || editingDisabled() || (allowEditing() && !editing())" [quantityDisabled]="
[showRemove]="allowRemove()" readonly() ||
!allowUpdateQuantity() ||
editingDisabled() ||
(requireEditingMode() && !editing())
"
[variantDisabled]="
readonly() ||
!allowUpdateVariant() ||
editingDisabled() ||
(requireEditingMode() && !editing())
"
[removeDisabled]="
readonly() || !allowDelete() || editingDisabled() || (requireEditingMode() && !editing())
"
[allowDelete]="allowDelete()"
(quantityChange)="onItemQuantityChange(idx, $event)" (quantityChange)="onItemQuantityChange(idx, $event)"
(variantChange)="onItemVariantChange(idx, $event)" (variantChange)="onItemVariantChange(idx, $event)"
(remove)="onItemRemove(idx)" (remove)="onItemRemove(idx)"

View File

@@ -1,7 +1,15 @@
:host { :host {
display: block; display: flex;
width: 100%; width: 100%;
height: 100%; min-height: 0;
max-height: 100%;
overflow: hidden;
}
.cart-shell {
flex: 1 1 auto;
min-height: 0;
max-height: 100%;
} }
.cart-header { .cart-header {

View File

@@ -175,6 +175,63 @@ describe('CartComponent', () => {
expect(removeItem).not.toHaveBeenCalled(); expect(removeItem).not.toHaveBeenCalled();
}); });
it('notifies the user and refreshes the cart when a mutation reports expiration', async () => {
const expirationMessage = 'La reserva de stock venció. Usá el carrito activo para continuar.';
const removeItem = vi.fn().mockReturnValue(
throwError(() => ({
error: {
code: 'stock_reservation.expired',
message: expirationMessage,
},
})),
);
const loadCart = vi.fn().mockReturnValue(of({}));
const danger = vi.fn();
await TestBed.configureTestingModule({
imports: [CartComponent],
providers: [
{
provide: CartService,
useValue: {
cart: signal(null).asReadonly(),
loadCart,
updateItemQuantity: vi.fn(),
removeItem,
},
},
{
provide: ModalService,
useValue: { openConfirmDelete: vi.fn().mockReturnValue(of(true)) },
},
{
provide: ToastService,
useValue: { success: vi.fn(), info: vi.fn(), danger },
},
],
}).compileComponents();
const fixture = TestBed.createComponent(CartComponent);
fixture.componentRef.setInput('items', [
{
cartItemId: 10,
imageUrl: null,
product: 'Producto vencido',
originalPrice: null,
discountedPrice: 1000,
discountPercentage: null,
attributes: [],
quantity: 1,
},
]);
fixture.detectChanges();
fixture.debugElement.query(By.css('app-cart-item')).triggerEventHandler('remove');
expect(danger).toHaveBeenCalledWith(expirationMessage);
expect(loadCart).toHaveBeenCalledOnce();
});
it('optimistically updates quantity and rolls back on error', async () => { it('optimistically updates quantity and rolls back on error', async () => {
vi.useFakeTimers(); vi.useFakeTimers();
const updateItemQuantity = vi.fn().mockReturnValue(throwError(() => new Error('Error'))); const updateItemQuantity = vi.fn().mockReturnValue(throwError(() => new Error('Error')));
@@ -340,7 +397,7 @@ describe('CartComponent', () => {
quantity: 1, quantity: 1,
}, },
]); ]);
fixture.componentRef.setInput('allowEditing', true); fixture.componentRef.setInput('requireEditingMode', true);
const editingChange = vi.fn(); const editingChange = vi.fn();
fixture.componentInstance.editing.subscribe(editingChange); fixture.componentInstance.editing.subscribe(editingChange);
fixture.detectChanges(); fixture.detectChanges();
@@ -367,6 +424,57 @@ describe('CartComponent', () => {
expect(editingChange).toHaveBeenLastCalledWith(false); expect(editingChange).toHaveBeenLastCalledWith(false);
}); });
it('emits Modificar as an action without toggling to Listo', async () => {
await TestBed.configureTestingModule({
imports: [CartComponent],
providers: [
{
provide: CartService,
useValue: {
cart: signal(null).asReadonly(),
updateItemQuantity: vi.fn(),
removeItem: vi.fn(),
},
},
{ provide: ModalService, useValue: {} },
{
provide: ToastService,
useValue: { success: vi.fn(), info: vi.fn(), danger: vi.fn() },
},
],
}).compileComponents();
const fixture = TestBed.createComponent(CartComponent);
fixture.componentRef.setInput('items', [
{
cartItemId: 10,
imageUrl: null,
product: 'Producto de prueba',
originalPrice: null,
discountedPrice: 1000,
discountPercentage: null,
attributes: [],
quantity: 1,
},
]);
fixture.componentRef.setInput('readonly', true);
fixture.componentRef.setInput('showModifyWhenReadonly', true);
fixture.componentRef.setInput('modifyAsAction', true);
const modify = vi.fn();
fixture.componentInstance.modify.subscribe(modify);
fixture.detectChanges();
const modifyButton = fixture.debugElement.query(By.css('.cart-edit-btn'));
expect(modifyButton.nativeElement.textContent.trim()).toBe('Modificar');
modifyButton.nativeElement.click();
fixture.detectChanges();
expect(modify).toHaveBeenCalledOnce();
expect(modifyButton.nativeElement.textContent.trim()).toBe('Modificar');
expect(fixture.componentInstance.editing()).toBe(false);
});
it('allows editing directly when the optional Modificar toggle is disabled', async () => { it('allows editing directly when the optional Modificar toggle is disabled', async () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [CartComponent], imports: [CartComponent],
@@ -408,7 +516,7 @@ describe('CartComponent', () => {
).toBe(false); ).toBe(false);
}); });
it('hides the edit toggle and disables quantity changes when editable is false', async () => { it('hides the edit toggle and disables quantity changes when quantity updates are false', async () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [CartComponent], imports: [CartComponent],
providers: [ providers: [
@@ -441,8 +549,9 @@ describe('CartComponent', () => {
quantity: 1, quantity: 1,
}, },
]); ]);
fixture.componentRef.setInput('allowEditing', true); fixture.componentRef.setInput('requireEditingMode', true);
fixture.componentRef.setInput('editable', false); fixture.componentRef.setInput('allowModify', false);
fixture.componentRef.setInput('allowUpdateQuantity', false);
const quantityChange = vi.fn(); const quantityChange = vi.fn();
fixture.componentInstance.itemQuantityChange.subscribe(quantityChange); fixture.componentInstance.itemQuantityChange.subscribe(quantityChange);
fixture.detectChanges(); fixture.detectChanges();

View File

@@ -53,19 +53,32 @@ export class CartComponent {
readonly total = input<number>(0); readonly total = input<number>(0);
readonly backgroundColor = input<string>('#ffffff'); readonly backgroundColor = input<string>('#ffffff');
readonly readonly = input<boolean>(false); readonly readonly = input<boolean>(false);
readonly editable = input<boolean>(true); readonly allowUpdateQuantity = input<boolean>(true);
readonly allowEditing = input<boolean>(false); readonly allowModify = input<boolean>(true);
readonly allowRemove = input<boolean>(true); readonly showModifyWhenReadonly = input<boolean>(false);
readonly modifyAsAction = input<boolean>(false);
readonly requireEditingMode = input<boolean>(false);
readonly allowUpdateVariant = input<boolean>(true);
readonly allowDelete = input<boolean>(true);
readonly persistQuantityChanges = input<boolean>(true); readonly persistQuantityChanges = input<boolean>(true);
readonly persistVariantChanges = input<boolean>(true);
readonly persistDeleteChanges = input<boolean>(true);
readonly editingDisabled = input<boolean>(false); readonly editingDisabled = input<boolean>(false);
readonly editing = model<boolean>(false); readonly editing = model<boolean>(false);
readonly closed = output<void>(); readonly closed = output<void>();
readonly modify = output<void>();
readonly itemQuantityChange = output<{ readonly itemQuantityChange = output<{
item: CartItemMock; item: CartItemMock;
index: number; index: number;
quantity: number; quantity: number;
}>(); }>();
readonly itemVariantChange = output<{
item: CartItemMock;
index: number;
variantId: number;
}>();
readonly itemRemove = output<{ item: CartItemMock; index: number }>();
protected readonly quantityOverrides = signal<Record<number, number>>({}); protected readonly quantityOverrides = signal<Record<number, number>>({});
protected readonly variantOverrides = signal<Record<number, number>>({}); protected readonly variantOverrides = signal<Record<number, number>>({});
@@ -85,11 +98,12 @@ export class CartComponent {
this.clearOverride(update.cartItemId); this.clearOverride(update.cartItemId);
}, },
error: (err: HttpErrorResponse) => { error: (err: HttpErrorResponse) => {
console.error('Error updating cart quantity', err);
const msg =
err.error?.message || 'Error al actualizar la cantidad del producto.';
this.toastService.danger(msg);
this.clearOverride(update.cartItemId); this.clearOverride(update.cartItemId);
this.handleMutationError(
err,
'Error al actualizar la cantidad del producto.',
'Error updating cart quantity',
);
}, },
}), }),
catchError(() => EMPTY), catchError(() => EMPTY),
@@ -125,7 +139,7 @@ export class CartComponent {
} }
protected onItemQuantityChange(index: number, newQuantity: number): void { protected onItemQuantityChange(index: number, newQuantity: number): void {
if (!this.editable()) { if (!this.allowUpdateQuantity()) {
return; return;
} }
@@ -170,11 +184,19 @@ export class CartComponent {
} }
protected onItemVariantChange(index: number, variantId: number): void { protected onItemVariantChange(index: number, variantId: number): void {
if (this.readonly() || !this.allowUpdateVariant() || this.editingDisabled()) return;
const item = this.items()[index]; const item = this.items()[index];
const cartItemId = item?.cartItemId; const cartItemId = item?.cartItemId;
if (!item || !cartItemId || variantId === this.getItemVariant(item)) return; if (!item || !cartItemId || variantId === this.getItemVariant(item)) return;
this.itemVariantChange.emit({ item, index, variantId });
if (!this.persistVariantChanges()) {
return;
}
this.variantOverrides.update((overrides) => ({ ...overrides, [cartItemId]: variantId })); this.variantOverrides.update((overrides) => ({ ...overrides, [cartItemId]: variantId }));
this.cartService this.cartService
.updateItemVariant(cartItemId, this.getItemQuantity(item), variantId) .updateItemVariant(cartItemId, this.getItemQuantity(item), variantId)
@@ -184,9 +206,12 @@ export class CartComponent {
this.toastService.success(response.message || 'Variante actualizada.'); this.toastService.success(response.message || 'Variante actualizada.');
}, },
error: (error: HttpErrorResponse) => { error: (error: HttpErrorResponse) => {
console.error('Error updating cart item variant', error);
this.clearVariantOverride(cartItemId); this.clearVariantOverride(cartItemId);
this.toastService.danger(error.error?.message || 'No se pudo actualizar la variante.'); this.handleMutationError(
error,
'No se pudo actualizar la variante.',
'Error updating cart item variant',
);
}, },
}); });
} }
@@ -200,6 +225,8 @@ export class CartComponent {
} }
protected onItemRemove(index: number): void { protected onItemRemove(index: number): void {
if (this.readonly() || !this.allowDelete() || this.editingDisabled()) return;
const target = this.resolveRemoveTarget(index); const target = this.resolveRemoveTarget(index);
if (!target) { if (!target) {
@@ -215,7 +242,14 @@ export class CartComponent {
}) })
.subscribe((confirmed) => { .subscribe((confirmed) => {
if (confirmed) { if (confirmed) {
this.removeItem(target.cartItemId); const item = this.items()[index];
if (item) {
this.itemRemove.emit({ item, index });
}
if (this.persistDeleteChanges()) {
this.removeItem(target.cartItemId);
}
} }
}); });
} }
@@ -225,7 +259,12 @@ export class CartComponent {
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total())); protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
protected toggleEditing(): void { protected toggleEditing(): void {
if (!this.editable() || this.editingDisabled()) { if (!this.allowModify() || this.editingDisabled()) {
return;
}
if (this.modifyAsAction()) {
this.modify.emit();
return; return;
} }
@@ -270,10 +309,29 @@ export class CartComponent {
this.toastService.info(msg); this.toastService.info(msg);
}, },
error: (err: HttpErrorResponse) => { error: (err: HttpErrorResponse) => {
console.error('Error removing item from cart', err); this.handleMutationError(
const msg = err.error?.message || 'Error al eliminar el producto del carrito.'; err,
this.toastService.danger(msg); 'Error al eliminar el producto del carrito.',
'Error removing item from cart',
);
}, },
}); });
} }
private handleMutationError(
error: HttpErrorResponse,
fallbackMessage: string,
logMessage: string,
): void {
console.error(logMessage, error);
this.toastService.danger(error.error?.message || fallbackMessage);
if (error.error?.code !== 'stock_reservation.expired') {
return;
}
this.cartService.loadCart(true).subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
});
}
} }

View File

@@ -31,9 +31,16 @@
<div <div
class="product-column-with-image__body p-3 d-flex flex-column align-items-center text-center flex-grow-1" class="product-column-with-image__body p-3 d-flex flex-column align-items-center text-center flex-grow-1"
> >
<h3 class="product-column-with-image__title text-uppercase text-black mb-4">{{ title() }}</h3> <h3 class="product-column-with-image__title text-uppercase text-black mb-4">
{{ title() }}
@if (unavailableMessage(); as message) {
<app-tooltip [message]="message" />
}
</h3>
<div class="product-column-with-image__prices d-flex align-items-center justify-content-center gap-2"> <div
class="product-column-with-image__prices d-flex align-items-center justify-content-center gap-2"
>
<span class="product-column-with-image__price-discounted text-primary"> <span class="product-column-with-image__price-discounted text-primary">
{{ formattedDiscountedPrice() }} {{ formattedDiscountedPrice() }}
</span> </span>
@@ -53,7 +60,12 @@
</div> </div>
<div class="product-column-with-image__action mt-auto w-100"> <div class="product-column-with-image__action mt-auto w-100">
<app-button variant="primary" class="w-100" (click)="buy.emit()"> <app-button
variant="primary"
class="w-100"
[disabled]="!!unavailableMessage()"
(click)="onBuy()"
>
{{ buttonText() }} {{ buttonText() }}
</app-button> </app-button>
</div> </div>

View File

@@ -2,10 +2,11 @@ import { NgOptimizedImage } from '@angular/common';
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core'; import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
import { ButtonComponent } from '../button/button.component'; import { ButtonComponent } from '../button/button.component';
import { TooltipComponent } from '../tooltip/tooltip.component';
@Component({ @Component({
selector: 'app-product-column-with-image', selector: 'app-product-column-with-image',
imports: [ButtonComponent, NgOptimizedImage], imports: [ButtonComponent, NgOptimizedImage, TooltipComponent],
templateUrl: './product-column-with-image.component.html', templateUrl: './product-column-with-image.component.html',
styleUrl: './product-column-with-image.component.scss', styleUrl: './product-column-with-image.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
@@ -18,9 +19,16 @@ export class ProductColumnWithImageComponent {
readonly transferPrice = input<number | null>(null); readonly transferPrice = input<number | null>(null);
readonly buttonText = input<string>('Comprar'); readonly buttonText = input<string>('Comprar');
readonly imagePriority = input<boolean>(false); readonly imagePriority = input<boolean>(false);
readonly unavailableMessage = input<string | null>(null);
readonly buy = output<void>(); readonly buy = output<void>();
protected onBuy(): void {
if (this.unavailableMessage()) return;
this.buy.emit();
}
readonly discountedPrice = computed(() => { readonly discountedPrice = computed(() => {
const original = this.originalPrice(); const original = this.originalPrice();
const discount = this.discount(); const discount = this.discount();

View File

@@ -12,6 +12,8 @@
[title]="item.nombre" [title]="item.nombre"
[description]="item.descripcion ?? ''" [description]="item.descripcion ?? ''"
[price]="price(item)" [price]="price(item)"
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
[unavailableMessage]="item.unavailable_message ?? null"
[variants]="item.variants ?? []" [variants]="item.variants ?? []"
[saving]="savingProductIds().has(item.id)" [saving]="savingProductIds().has(item.id)"
(buy)="emitRowBuy(item, $event)" (buy)="emitRowBuy(item, $event)"
@@ -23,6 +25,8 @@
[title]="item.nombre" [title]="item.nombre"
[description]="item.descripcion ?? ''" [description]="item.descripcion ?? ''"
[price]="price(item)" [price]="price(item)"
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
[unavailableMessage]="item.unavailable_message ?? null"
[variants]="item.variants ?? []" [variants]="item.variants ?? []"
[saving]="savingProductIds().has(item.id)" [saving]="savingProductIds().has(item.id)"
(buy)="emitColumnBuy(item, $event)" (buy)="emitColumnBuy(item, $event)"
@@ -36,7 +40,8 @@
[description]="item.descripcion ?? ''" [description]="item.descripcion ?? ''"
[price]="price(item)" [price]="price(item)"
[imageUrl]="loadImages() ? (item.image ?? null) : null" [imageUrl]="loadImages() ? (item.image ?? null) : null"
[disabled]="loading()" [unavailableMessage]="item.unavailable_message ?? null"
[disabled]="loading() || !!item.unavailable_message"
(buy)="emitTicketBuy(item, $event)" (buy)="emitTicketBuy(item, $event)"
/> />
} }
@@ -45,6 +50,7 @@
[imageUrl]="loadImages() ? (item.image ?? null) : null" [imageUrl]="loadImages() ? (item.image ?? null) : null"
[title]="item.nombre" [title]="item.nombre"
[originalPrice]="price(item)" [originalPrice]="price(item)"
[unavailableMessage]="item.unavailable_message ?? null"
[imagePriority]="loadImages() && index < 4" [imagePriority]="loadImages() && index < 4"
(buy)="emitProductDetailBuy(item)" (buy)="emitProductDetailBuy(item)"
/> />

View File

@@ -193,8 +193,8 @@ describe('ProductListComponent', () => {
const itemWithVariants: ProductListItem = { const itemWithVariants: ProductListItem = {
...items[0], ...items[0],
variants: [ variants: [
{ id: 91, stock_tecnico: 3, values: { fecha: '10 de octubre' } }, { id: 91, maximum_addable_quantity: 3, values: { fecha: '10 de octubre' } },
{ id: 92, stock_tecnico: 4, values: { fecha: '11 de octubre' } }, { id: 92, maximum_addable_quantity: 4, values: { fecha: '11 de octubre' } },
], ],
}; };
const fixture = await render('column_with_cart', [itemWithVariants]); const fixture = await render('column_with_cart', [itemWithVariants]);
@@ -214,6 +214,58 @@ describe('ProductListComponent', () => {
}); });
}); });
it('caps the quantity at the selected variant maximum', async () => {
const itemWithVariants: ProductListItem = {
...items[0],
variants: [
{
id: 91,
maximum_addable_quantity: 2,
values: { fecha: '10 de octubre' },
},
],
};
const fixture = await render('column_with_cart', [itemWithVariants]);
await fixture.whenStable();
fixture.detectChanges();
const increase = fixture.nativeElement.querySelector(
'.quantity-selector__button:last-child',
) as HTMLButtonElement;
increase.click();
fixture.detectChanges();
expect(
(fixture.nativeElement as HTMLElement).querySelector('.quantity-selector__value')
?.textContent,
).toContain('2');
expect(increase.disabled).toBe(true);
});
it('disables purchase actions when the selected variant maximum is zero', async () => {
const unavailableItem: ProductListItem = {
...items[0],
variants: [
{
id: 91,
maximum_addable_quantity: 0,
values: { fecha: '10 de octubre' },
},
],
};
const fixture = await render('row', [unavailableItem]);
await fixture.whenStable();
fixture.detectChanges();
const buttons = Array.from(
(fixture.nativeElement as HTMLElement).querySelectorAll<HTMLButtonElement>(
'.product-row-card__buttons button',
),
);
expect(buttons).toHaveLength(2);
expect(buttons.every((button) => button.disabled)).toBe(true);
});
it('renders pagination and emits the requested page', async () => { it('renders pagination and emits the requested page', async () => {
const fixture = await render('row'); const fixture = await render('row');
const pageChangeSpy = vi.fn(); const pageChangeSpy = vi.fn();
@@ -252,7 +304,7 @@ describe('ProductListComponent', () => {
{ {
id: 401, id: 401,
precio: '10000.00', precio: '10000.00',
stock_tecnico: 1, maximum_addable_quantity: 1,
values: { values: {
tipo: { value: 'vip', label: 'VIP' }, tipo: { value: 'vip', label: 'VIP' },
sector: { value: 'a', label: 'Sector A' }, sector: { value: 'a', label: 'Sector A' },
@@ -263,7 +315,7 @@ describe('ProductListComponent', () => {
{ {
id: 402, id: 402,
precio: '12000.00', precio: '12000.00',
stock_tecnico: 1, maximum_addable_quantity: 1,
values: { values: {
tipo: { value: 'vip', label: 'VIP' }, tipo: { value: 'vip', label: 'VIP' },
sector: { value: 'a', label: 'Sector A' }, sector: { value: 'a', label: 'Sector A' },

View File

@@ -3,6 +3,9 @@
<div class="product-row-card__info d-flex flex-column justify-content-center flex-grow-1"> <div class="product-row-card__info d-flex flex-column justify-content-center flex-grow-1">
<h3 class="product-row-card__title text-uppercase mb-1 m-0"> <h3 class="product-row-card__title text-uppercase mb-1 m-0">
{{ title() }} {{ title() }}
@if (effectiveUnavailableMessage(); as message) {
<app-tooltip [message]="message" />
}
</h3> </h3>
@if (effectiveDescription()) { @if (effectiveDescription()) {
<p class="product-row-card__description m-0 mt-1"> <p class="product-row-card__description m-0 mt-1">
@@ -21,7 +24,11 @@
[(selectedVariant)]="selectedVariant" [(selectedVariant)]="selectedVariant"
/> />
<app-quantity-selector [(quantity)]="quantity"></app-quantity-selector> <app-quantity-selector
[(quantity)]="quantity"
[max]="effectiveMaximum()"
[disabled]="unavailable()"
/>
</div> </div>
<span class="product-row-card__price text-primary"> <span class="product-row-card__price text-primary">
@@ -31,10 +38,16 @@
<div class="product-row-card__buttons"> <div class="product-row-card__buttons">
<div class="product-row-card__btn-wrapper"> <div class="product-row-card__btn-wrapper">
<app-button variant="primary" (click)="onBuy()"> Comprar </app-button> <app-button variant="primary" [disabled]="unavailable()" (click)="onBuy()">
Comprar
</app-button>
</div> </div>
<div class="product-row-card__btn-wrapper"> <div class="product-row-card__btn-wrapper">
<app-button variant="secondary" [disabled]="saving()" (click)="onAddToCart()"> <app-button
variant="secondary"
[disabled]="saving() || unavailable()"
(click)="onAddToCart()"
>
{{ saving() ? 'Guardando' : 'Agregar al carrito' }} {{ saving() ? 'Guardando' : 'Agregar al carrito' }}
</app-button> </app-button>
</div> </div>

View File

@@ -1,6 +1,15 @@
import { ChangeDetectionStrategy, Component, computed, input, model, output } from '@angular/core'; import {
ChangeDetectionStrategy,
Component,
computed,
effect,
input,
model,
output,
} from '@angular/core';
import { ButtonComponent } from '../button/button.component'; import { ButtonComponent } from '../button/button.component';
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component'; import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
import { TooltipComponent } from '../tooltip/tooltip.component';
import { import {
VariantSelectorComponent, VariantSelectorComponent,
VariantSelectorVariant, VariantSelectorVariant,
@@ -10,13 +19,14 @@ export interface Variant extends VariantSelectorVariant {
label?: string; label?: string;
descripcion?: string | null; descripcion?: string | null;
precio?: string | number; precio?: string | number;
stock_tecnico?: number | null; maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
} }
@Component({ @Component({
selector: 'app-product-row-card', selector: 'app-product-row-card',
standalone: true, standalone: true,
imports: [ButtonComponent, QuantitySelectorComponent, VariantSelectorComponent], imports: [ButtonComponent, QuantitySelectorComponent, TooltipComponent, VariantSelectorComponent],
templateUrl: './product-row-card.component.html', templateUrl: './product-row-card.component.html',
styleUrl: './product-row-card.component.scss', styleUrl: './product-row-card.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
@@ -26,6 +36,8 @@ export class ProductRowCardComponent {
readonly title = input<string>(''); readonly title = input<string>('');
readonly description = input<string>(''); readonly description = input<string>('');
readonly price = input<number>(0); readonly price = input<number>(0);
readonly maximumAddableQuantity = input<number | null>(null);
readonly unavailableMessage = input<string | null>(null);
readonly variants = input<Variant[]>([]); readonly variants = input<Variant[]>([]);
readonly saving = input(false); readonly saving = input(false);
@@ -48,11 +60,32 @@ export class ProductRowCardComponent {
return Number.isFinite(variantPrice) ? variantPrice : this.price(); return Number.isFinite(variantPrice) ? variantPrice : this.price();
}); });
protected readonly effectiveMaximum = computed(
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
);
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
protected readonly effectiveUnavailableMessage = computed(() => {
const selectedVariant = this.selectedVariantData();
return selectedVariant
? (selectedVariant.unavailable_message ?? null)
: this.unavailableMessage();
});
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice())); readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
constructor() {
effect(() => {
const maximum = this.effectiveMaximum();
if (maximum !== null && maximum > 0 && this.quantity() > maximum) {
this.quantity.set(maximum);
}
});
}
protected onAddToCart(): void { protected onAddToCart(): void {
if (this.saving()) { if (this.saving() || this.unavailable()) {
return; return;
} }
@@ -63,6 +96,8 @@ export class ProductRowCardComponent {
} }
protected onBuy(): void { protected onBuy(): void {
if (this.unavailable()) return;
this.buy.emit({ this.buy.emit({
quantity: this.quantity(), quantity: this.quantity(),
variant: this.selectedVariant(), variant: this.selectedVariant(),

View File

@@ -1,7 +1,12 @@
<article class="ticket-selector"> <article class="ticket-selector">
<header class="ticket-selector__header"> <header class="ticket-selector__header">
<div> <div>
<h3 class="ticket-selector__title">{{ title() }}</h3> <h3 class="ticket-selector__title">
{{ title() }}
@if (unavailableMessage(); as message) {
<app-tooltip [message]="message" />
}
</h3>
@if (description()) { @if (description()) {
<p class="ticket-selector__description">{{ description() }}</p> <p class="ticket-selector__description">{{ description() }}</p>
} }

View File

@@ -28,6 +28,7 @@ import { ModalService } from '../../../core/services/modal.service';
import { ToastService } from '../../../core/services/toast.service'; import { ToastService } from '../../../core/services/toast.service';
import { ButtonComponent } from '../button/button.component'; import { ButtonComponent } from '../button/button.component';
import { IconButtonComponent } from '../icon-button/icon-button.component'; import { IconButtonComponent } from '../icon-button/icon-button.component';
import { TooltipComponent } from '../tooltip/tooltip.component';
type TicketSelectionStatus = type TicketSelectionStatus =
| 'selecting' | 'selecting'
@@ -56,7 +57,7 @@ interface TicketSelectionRow {
@Component({ @Component({
selector: 'app-product-ticket-selector', selector: 'app-product-ticket-selector',
imports: [ButtonComponent, IconButtonComponent], imports: [ButtonComponent, IconButtonComponent, TooltipComponent],
templateUrl: './product-ticket-selector.component.html', templateUrl: './product-ticket-selector.component.html',
styleUrl: './product-ticket-selector.component.scss', styleUrl: './product-ticket-selector.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
@@ -80,6 +81,7 @@ export class ProductTicketSelectorComponent {
readonly price = input<number>(0); readonly price = input<number>(0);
readonly imageUrl = input<string | null>(null); readonly imageUrl = input<string | null>(null);
readonly disabled = input(false); readonly disabled = input(false);
readonly unavailableMessage = input<string | null>(null);
readonly buy = output<number[]>(); readonly buy = output<number[]>();
@@ -361,7 +363,7 @@ export class ProductTicketSelectorComponent {
return { return {
id: item.variant.id, id: item.variant.id,
precio: item.variant.precio, precio: item.variant.precio,
stock_tecnico: item.variant.stock_tecnico, maximum_addable_quantity: item.variant.stock_tecnico,
values: item.variant.values, values: item.variant.values,
}; };
} }

View File

@@ -1,6 +1,11 @@
<article class="product-vertical-with-cart-card"> <article class="product-vertical-with-cart-card">
<div class="product-vertical-with-cart-card__content"> <div class="product-vertical-with-cart-card__content">
<h3 class="product-vertical-with-cart-card__title">{{ title() }}</h3> <h3 class="product-vertical-with-cart-card__title">
{{ title() }}
@if (effectiveUnavailableMessage(); as message) {
<app-tooltip [message]="message" />
}
</h3>
@if (effectiveDescription()) { @if (effectiveDescription()) {
<p class="product-vertical-with-cart-card__description">{{ effectiveDescription() }}</p> <p class="product-vertical-with-cart-card__description">{{ effectiveDescription() }}</p>
@@ -11,13 +16,21 @@
@if (!hasVariants()) { @if (!hasVariants()) {
<div class="product-vertical-with-cart-card__summary"> <div class="product-vertical-with-cart-card__summary">
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span> <span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
<app-quantity-selector [(quantity)]="quantity" /> <app-quantity-selector
[(quantity)]="quantity"
[max]="effectiveMaximum()"
[disabled]="unavailable()"
/>
</div> </div>
} @else { } @else {
<div class="product-vertical-with-cart-card__variants"> <div class="product-vertical-with-cart-card__variants">
<div class="product-vertical-with-cart-card__summary"> <div class="product-vertical-with-cart-card__summary">
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span> <span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
<app-quantity-selector [(quantity)]="quantity" /> <app-quantity-selector
[(quantity)]="quantity"
[max]="effectiveMaximum()"
[disabled]="unavailable()"
/>
</div> </div>
<div class="product-vertical-with-cart-card__variant-selectors"> <div class="product-vertical-with-cart-card__variant-selectors">
@@ -29,14 +42,14 @@
<div class="product-vertical-with-cart-card__actions"> <div class="product-vertical-with-cart-card__actions">
<app-button <app-button
variant="primary" variant="primary"
[disabled]="hasVariants() && selectedVariant() === null" [disabled]="unavailable() || (hasVariants() && selectedVariant() === null)"
(click)="onBuy()" (click)="onBuy()"
> >
Comprar Comprar
</app-button> </app-button>
<app-button <app-button
variant="secondary" variant="secondary"
[disabled]="saving() || (hasVariants() && selectedVariant() === null)" [disabled]="saving() || unavailable() || (hasVariants() && selectedVariant() === null)"
(click)="onAddToCart()" (click)="onAddToCart()"
> >
{{ saving() ? 'Guardando' : 'Agregar al carrito' }} {{ saving() ? 'Guardando' : 'Agregar al carrito' }}

View File

@@ -56,6 +56,23 @@ describe('ProductVerticalWithCartCardComponent', () => {
).toBeNull(); ).toBeNull();
}); });
it('shows the backend availability message with the reusable tooltip', async () => {
const fixture = await createComponent();
fixture.componentRef.setInput('maximumAddableQuantity', 0);
fixture.componentRef.setInput(
'unavailableMessage',
'Alcanzaste el cupo máximo permitido para este producto.',
);
fixture.detectChanges();
const tooltip = (fixture.nativeElement as HTMLElement).querySelector('app-tooltip');
expect(tooltip?.querySelector('i.fa-solid.fa-circle-info')).not.toBeNull();
expect(tooltip?.textContent).toContain(
'Alcanzaste el cupo máximo permitido para este producto.',
);
});
it('updates the quantity with the reusable quantity selector', async () => { it('updates the quantity with the reusable quantity selector', async () => {
const fixture = await createComponent(); const fixture = await createComponent();
const buttons = fixture.nativeElement.querySelectorAll( const buttons = fixture.nativeElement.querySelectorAll(

View File

@@ -1,7 +1,16 @@
import { ChangeDetectionStrategy, Component, computed, input, model, output } from '@angular/core'; import {
ChangeDetectionStrategy,
Component,
computed,
effect,
input,
model,
output,
} from '@angular/core';
import { ButtonComponent } from '../button/button.component'; import { ButtonComponent } from '../button/button.component';
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component'; import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
import { TooltipComponent } from '../tooltip/tooltip.component';
import { import {
VariantSelectorComponent, VariantSelectorComponent,
VariantSelectorVariant, VariantSelectorVariant,
@@ -10,11 +19,13 @@ import {
export interface VerticalCartVariant extends VariantSelectorVariant { export interface VerticalCartVariant extends VariantSelectorVariant {
descripcion?: string | null; descripcion?: string | null;
precio?: string | number; precio?: string | number;
maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
} }
@Component({ @Component({
selector: 'app-product-vertical-with-cart-card', selector: 'app-product-vertical-with-cart-card',
imports: [ButtonComponent, QuantitySelectorComponent, VariantSelectorComponent], imports: [ButtonComponent, QuantitySelectorComponent, TooltipComponent, VariantSelectorComponent],
templateUrl: './product-vertical-with-cart-card.component.html', templateUrl: './product-vertical-with-cart-card.component.html',
styleUrl: './product-vertical-with-cart-card.component.scss', styleUrl: './product-vertical-with-cart-card.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
@@ -23,6 +34,8 @@ export class ProductVerticalWithCartCardComponent {
readonly title = input<string>(''); readonly title = input<string>('');
readonly description = input<string>(''); readonly description = input<string>('');
readonly price = input<number>(0); readonly price = input<number>(0);
readonly maximumAddableQuantity = input<number | null>(null);
readonly unavailableMessage = input<string | null>(null);
readonly variants = input<VerticalCartVariant[]>([]); readonly variants = input<VerticalCartVariant[]>([]);
readonly saving = input(false); readonly saving = input(false);
@@ -45,9 +58,30 @@ export class ProductVerticalWithCartCardComponent {
}); });
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice())); protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
protected readonly hasVariants = computed(() => this.variants().length > 0); protected readonly hasVariants = computed(() => this.variants().length > 0);
protected readonly effectiveMaximum = computed(
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
);
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
protected readonly effectiveUnavailableMessage = computed(() => {
const selectedVariant = this.selectedVariantData();
return selectedVariant
? (selectedVariant.unavailable_message ?? null)
: this.unavailableMessage();
});
constructor() {
effect(() => {
const maximum = this.effectiveMaximum();
if (maximum !== null && maximum > 0 && this.quantity() > maximum) {
this.quantity.set(maximum);
}
});
}
protected onAddToCart(): void { protected onAddToCart(): void {
if (this.saving()) { if (this.saving() || this.unavailable()) {
return; return;
} }
@@ -55,6 +89,8 @@ export class ProductVerticalWithCartCardComponent {
} }
protected onBuy(): void { protected onBuy(): void {
if (this.unavailable()) return;
this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() }); this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
} }

View File

@@ -1,25 +1,27 @@
<div class="stepper-container"> <div class="stepper-container">
<!-- Horizontal indicator bar --> <!-- Horizontal indicator bar -->
<div class="stepper-header"> <div class="stepper-header" [class.is-disabled]="disabled()" [attr.aria-disabled]="disabled()">
@for (step of steps(); track step; let i = $index; let last = $last) { @for (step of steps(); track step; let i = $index; let last = $last) {
<div <div
class="stepper-header__item" class="stepper-header__item"
[ngClass]="{ [ngClass]="{
'is-active': currentStepIndex() === i, 'is-active': currentStepIndex() === i,
'is-completed': currentStepIndex() > i 'is-completed': currentStepIndex() > i,
}" }"
> >
<!-- Connecting line before (except first) --> <!-- Connecting line before (except first) -->
@if (i > 0) { @if (i > 0) {
<div class="stepper-header__line" [ngClass]="{ 'is-completed': currentStepIndex() > i - 1 }"></div> <div
class="stepper-header__line"
[ngClass]="{ 'is-completed': currentStepIndex() > i - 1 }"
></div>
} }
<!-- Circle indicator --> <!-- Circle indicator -->
<div <div
class="stepper-header__circle" class="stepper-header__circle"
[attr.aria-label]="step.label()" [attr.aria-label]="step.label()"
[class.is-clickable]="currentStepIndex() > i" [class.is-clickable]="!disabled() && currentStepIndex() > i"
(click)="goToStep(i)" (click)="goToStep(i)"
></div> ></div>
@@ -33,5 +35,4 @@
<div class="stepper-body"> <div class="stepper-body">
<ng-content></ng-content> <ng-content></ng-content>
</div> </div>
</div> </div>

View File

@@ -13,6 +13,14 @@
margin-bottom: 2rem; margin-bottom: 2rem;
position: relative; position: relative;
&.is-disabled {
opacity: 0.5;
.stepper-header__circle {
cursor: not-allowed;
}
}
&__item { &__item {
display: flex; display: flex;
flex-direction: column; flex-direction: column;

View File

@@ -6,7 +6,7 @@ import { StepComponent } from './step.component';
@Component({ @Component({
imports: [StepperComponent, StepComponent], imports: [StepperComponent, StepComponent],
template: ` template: `
<app-stepper #stepper> <app-stepper #stepper [disabled]="stepperDisabled()">
<app-step label="Step 1" [isValid]="step1Valid()"> <app-step label="Step 1" [isValid]="step1Valid()">
<div id="content-1">Content 1</div> <div id="content-1">Content 1</div>
</app-step> </app-step>
@@ -20,6 +20,7 @@ class TestHostComponent {
@ViewChild('stepper') stepper!: StepperComponent; @ViewChild('stepper') stepper!: StepperComponent;
step1Valid = signal(true); step1Valid = signal(true);
step2Valid = signal(true); step2Valid = signal(true);
stepperDisabled = signal(false);
} }
describe('StepperComponent & StepComponent', () => { describe('StepperComponent & StepComponent', () => {
@@ -137,4 +138,28 @@ describe('StepperComponent & StepComponent', () => {
expect(component.stepper.currentStepIndex()).toBe(0); expect(component.stepper.currentStepIndex()).toBe(0);
expect(fixture.nativeElement.querySelector('#content-1')).not.toBeNull(); expect(fixture.nativeElement.querySelector('#content-1')).not.toBeNull();
}); });
it('blocks all navigation and shows visual feedback while disabled', async () => {
const { fixture, component } = await setup();
component.stepperDisabled.set(true);
fixture.detectChanges();
component.stepper.next();
expect(component.stepper.currentStepIndex()).toBe(0);
component.stepperDisabled.set(false);
fixture.detectChanges();
component.stepper.next();
expect(component.stepper.currentStepIndex()).toBe(1);
component.stepperDisabled.set(true);
fixture.detectChanges();
component.stepper.previous();
component.stepper.goToStep(0);
expect(component.stepper.currentStepIndex()).toBe(1);
const header = fixture.nativeElement.querySelector('.stepper-header');
expect(header.classList.contains('is-disabled')).toBe(true);
expect(header.getAttribute('aria-disabled')).toBe('true');
});
}); });

View File

@@ -18,9 +18,12 @@ import { NgClass } from '@angular/common';
export class StepperComponent { export class StepperComponent {
readonly steps = contentChildren(StepComponent); readonly steps = contentChildren(StepComponent);
readonly initialStepIndex = input(0); readonly initialStepIndex = input(0);
readonly disabled = input(false);
readonly currentStepIndex = linkedSignal(() => this.initialStepIndex()); readonly currentStepIndex = linkedSignal(() => this.initialStepIndex());
next() { next() {
if (this.disabled()) return;
const currentSteps = this.steps(); const currentSteps = this.steps();
const currentIndex = this.currentStepIndex(); const currentIndex = this.currentStepIndex();
if (currentIndex < currentSteps.length - 1) { if (currentIndex < currentSteps.length - 1) {
@@ -32,6 +35,8 @@ export class StepperComponent {
} }
previous() { previous() {
if (this.disabled()) return;
const currentIndex = this.currentStepIndex(); const currentIndex = this.currentStepIndex();
if (currentIndex > 0) { if (currentIndex > 0) {
this.currentStepIndex.set(currentIndex - 1); this.currentStepIndex.set(currentIndex - 1);
@@ -39,6 +44,8 @@ export class StepperComponent {
} }
goToStep(index: number) { goToStep(index: number) {
if (this.disabled()) return;
const targetIndex = index; const targetIndex = index;
// Only allow navigating to completed steps or the current one // Only allow navigating to completed steps or the current one
if (targetIndex < this.currentStepIndex()) { if (targetIndex < this.currentStepIndex()) {

View File

@@ -0,0 +1,11 @@
<button
type="button"
class="tooltip-trigger"
[attr.aria-describedby]="tooltipId"
[attr.aria-label]="message()"
>
<i class="fa-solid fa-circle-info" aria-hidden="true"></i>
<span class="tooltip-message" [id]="tooltipId" role="tooltip">
{{ message() }}
</span>
</button>

View File

@@ -0,0 +1,62 @@
:host {
display: inline-flex;
align-items: center;
margin-left: 0.25rem;
vertical-align: middle;
}
.tooltip-trigger {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
background: transparent;
color: var(--tenant-primary, var(--color-primary, #0d6efd));
font-size: 1em;
line-height: inherit;
&:focus-visible {
border-radius: 50%;
outline: 2px solid currentColor;
outline-offset: 2px;
}
&:hover .tooltip-message,
&:focus-visible .tooltip-message {
visibility: visible;
opacity: 1;
transform: translate(-50%, -0.25rem);
}
}
.tooltip-message {
position: absolute;
z-index: 1100;
bottom: calc(100% + 0.625rem);
left: 50%;
width: max-content;
max-width: min(16rem, 75vw);
padding: 0.5rem 0.75rem;
border-radius: 0.375rem;
border: 1px solid var(--tenant-primary, var(--color-primary, #0d6efd));
background: #fff;
color: #212529;
font-family: inherit;
font-size: 0.75rem;
font-weight: 400;
line-height: 1.35;
text-align: center;
text-transform: none;
letter-spacing: normal;
white-space: normal;
visibility: hidden;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 0);
transition:
opacity 0.15s ease,
transform 0.15s ease,
visibility 0.15s ease;
}

View File

@@ -0,0 +1,32 @@
import { TestBed, getTestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
import { TooltipComponent } from './tooltip.component';
describe('TooltipComponent', () => {
beforeAll(() => {
try {
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
} catch {
// Test environment may already be initialized by another setup entrypoint.
}
});
afterEach(() => TestBed.resetTestingModule());
it('renders the reusable danger information tooltip', async () => {
await TestBed.configureTestingModule({ imports: [TooltipComponent] }).compileComponents();
const fixture = TestBed.createComponent(TooltipComponent);
fixture.componentRef.setInput('message', 'Este producto no tiene stock disponible.');
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
const trigger = element.querySelector('.tooltip-trigger');
const message = element.querySelector('.tooltip-message');
expect(trigger?.querySelector('i.fa-solid.fa-circle-info')).not.toBeNull();
expect(message?.textContent?.trim()).toBe('Este producto no tiene stock disponible.');
expect(trigger?.getAttribute('aria-describedby')).toBe(message?.id);
});
});

View File

@@ -0,0 +1,14 @@
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
let nextTooltipId = 0;
@Component({
selector: 'app-tooltip',
templateUrl: './tooltip.component.html',
styleUrl: './tooltip.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TooltipComponent {
readonly message = input.required<string>();
protected readonly tooltipId = `app-tooltip-${nextTooltipId++}`;
}

View File

@@ -1,5 +1,5 @@
export const environment = { export const environment = {
production: false, production: true,
nombre:"Homologación - activo", nombre:"Homologación - activo",
url:"https://backend.qa.shopit.com.ar/api/", url:"https://backend.qa.shopit.com.ar/api/",
urlDescarga:"url/" urlDescarga:"url/"

View File

@@ -5,7 +5,7 @@
<title>ShopitFront</title> <title>ShopitFront</title>
<base href="/"> <base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E">
</head> </head>
<body> <body>
<app-root></app-root> <app-root></app-root>

View File

@@ -6,6 +6,15 @@
@import '../node_modules/bootstrap/scss/bootstrap'; @import '../node_modules/bootstrap/scss/bootstrap';
html,
body,
app-root {
width: 100%;
min-height: 100%;
margin: 0;
background: #f5f5f5;
}
:root, :root,
app-root { app-root {
--border-color: #dddddd; --border-color: #dddddd;