Compare commits
13 Commits
fix/minor_
...
cfa1091116
| Author | SHA1 | Date | |
|---|---|---|---|
| cfa1091116 | |||
| d0b1607ff4 | |||
| 92546a28c0 | |||
| ce26fb5d1a | |||
| 38a57adf55 | |||
| e1d9590905 | |||
| 00a01e1a8e | |||
| 56e011bc7a | |||
| 5c6a03b10d | |||
| cc446433f6 | |||
| 2d0664a7c7 | |||
| 2192eea09f | |||
| 755d6a9903 |
@@ -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",
|
||||||
|
|||||||
@@ -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">
|
||||||
|
@if (address) {
|
||||||
<div class="d-flex align-items-center gap-2">
|
<div class="d-flex align-items-center gap-2">
|
||||||
<i class="fa-solid fa-location-dot" aria-hidden="true"></i>
|
<i class="fa-solid fa-location-dot" aria-hidden="true"></i>
|
||||||
<span>Av. San Lorenzo 1542, Rosario</span>
|
<span>{{ address }}</span>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
@if (phone) {
|
||||||
<div class="d-flex align-items-center gap-2">
|
<div class="d-flex align-items-center gap-2">
|
||||||
<i class="fa-solid fa-phone" aria-hidden="true"></i>
|
<i class="fa-solid fa-phone" aria-hidden="true"></i>
|
||||||
<span>54 9 (0341) 6658247</span>
|
<span>{{ phone }}</span>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p class="mb-0 small store-layout__muted-text store-layout__copyright">
|
<p class="mb-0 small store-layout__muted-text store-layout__copyright">
|
||||||
|
|||||||
@@ -27,5 +27,7 @@ export class StoreFooterComponent {
|
|||||||
@Input() logoUrl: string | null = null;
|
@Input() logoUrl: string | null = null;
|
||||||
@Input() backgroundImageUrl: string | null = null;
|
@Input() backgroundImageUrl: string | null = null;
|
||||||
@Input() storeName: string | null = null;
|
@Input() storeName: string | null = null;
|
||||||
|
@Input() address: string | null = null;
|
||||||
|
@Input() phone: string | null = null;
|
||||||
readonly logoutClick = output<void>();
|
readonly logoutClick = output<void>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,7 +29,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 +67,8 @@
|
|||||||
[logoUrl]="tenant()?.footer_logo ?? null"
|
[logoUrl]="tenant()?.footer_logo ?? null"
|
||||||
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
|
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
|
||||||
[storeName]="tenant()?.nombre ?? null"
|
[storeName]="tenant()?.nombre ?? null"
|
||||||
|
[address]="tenant()?.address ?? null"
|
||||||
|
[phone]="tenant()?.phone ?? null"
|
||||||
(logoutClick)="onLogoutClick()"
|
(logoutClick)="onLogoutClick()"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -21,6 +21,8 @@
|
|||||||
|
|
||||||
.store-layout__cart-dropdown {
|
.store-layout__cart-dropdown {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
top: 100px;
|
top: 100px;
|
||||||
right: calc((100% - 1320px) / 2 + 1.5rem);
|
right: calc((100% - 1320px) / 2 + 1.5rem);
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@@ -34,6 +36,10 @@
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
animation: store-layout-slide-down 0.2s ease-out;
|
animation: store-layout-slide-down 0.2s ease-out;
|
||||||
|
|
||||||
|
> app-cart {
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 1400px) {
|
@media (max-width: 1400px) {
|
||||||
right: 1.5rem;
|
right: 1.5rem;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,15 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { provideRouter, Router } from '@angular/router';
|
import {
|
||||||
|
ActivatedRoute,
|
||||||
|
convertToParamMap,
|
||||||
|
ParamMap,
|
||||||
|
provideRouter,
|
||||||
|
Router,
|
||||||
|
} from '@angular/router';
|
||||||
|
|
||||||
import { of } from 'rxjs';
|
import { BehaviorSubject, of } from 'rxjs';
|
||||||
|
|
||||||
import { Tenant } from '../../services/tenant.interface';
|
import { Tenant } from '../../services/tenant.interface';
|
||||||
import { TenantService } from '../../services/tenant.service';
|
import { TenantService } from '../../services/tenant.service';
|
||||||
@@ -22,6 +28,8 @@ const tenant: Tenant = {
|
|||||||
codigo: 'test',
|
codigo: 'test',
|
||||||
nombre: 'Test Tenant',
|
nombre: 'Test Tenant',
|
||||||
dominio: 'localhost',
|
dominio: 'localhost',
|
||||||
|
address: 'Calle Test 123, Rosario',
|
||||||
|
phone: '+54 341 555 1234',
|
||||||
primary_color: '#6376F3',
|
primary_color: '#6376F3',
|
||||||
secondary_color: '#A0A0A0',
|
secondary_color: '#A0A0A0',
|
||||||
danger_color: '#FF8888',
|
danger_color: '#FF8888',
|
||||||
@@ -32,6 +40,13 @@ const tenant: Tenant = {
|
|||||||
footer_logo: 'https://example.com/footer.png',
|
footer_logo: 'https://example.com/footer.png',
|
||||||
header_bg_image: 'https://example.com/header-background.png',
|
header_bg_image: 'https://example.com/header-background.png',
|
||||||
footer_bg_image: 'https://example.com/footer-background.png',
|
footer_bg_image: 'https://example.com/footer-background.png',
|
||||||
|
cart_editing_policy: {
|
||||||
|
code: 'full',
|
||||||
|
allow_modify: true,
|
||||||
|
allow_delete: true,
|
||||||
|
allow_update_quantity: true,
|
||||||
|
allow_update_variant: true,
|
||||||
|
},
|
||||||
categories: [],
|
categories: [],
|
||||||
menues: [
|
menues: [
|
||||||
{
|
{
|
||||||
@@ -133,11 +148,13 @@ describe('StoreLayoutComponent', () => {
|
|||||||
let cartState = signal<Cart | null>(null);
|
let cartState = signal<Cart | null>(null);
|
||||||
let authUserState = signal<AuthUser | null>(null);
|
let authUserState = signal<AuthUser | null>(null);
|
||||||
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
||||||
|
let queryParamMapState: BehaviorSubject<ParamMap>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
tenantState = signal<Tenant | null>(tenant);
|
tenantState = signal<Tenant | null>(tenant);
|
||||||
cartState = signal<Cart | null>(null);
|
cartState = signal<Cart | null>(null);
|
||||||
authUserState = signal<AuthUser | null>(null);
|
authUserState = signal<AuthUser | null>(null);
|
||||||
|
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
||||||
const isAuthenticatedState = signal(false);
|
const isAuthenticatedState = signal(false);
|
||||||
checkoutServiceStub = {
|
checkoutServiceStub = {
|
||||||
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
|
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
|
||||||
@@ -147,6 +164,10 @@ describe('StoreLayoutComponent', () => {
|
|||||||
imports: [StoreLayoutComponent],
|
imports: [StoreLayoutComponent],
|
||||||
providers: [
|
providers: [
|
||||||
provideRouter([]),
|
provideRouter([]),
|
||||||
|
{
|
||||||
|
provide: ActivatedRoute,
|
||||||
|
useValue: { queryParamMap: queryParamMapState.asObservable() },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
provide: TenantService,
|
provide: TenantService,
|
||||||
useValue: {
|
useValue: {
|
||||||
@@ -206,6 +227,19 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull();
|
expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('opens the cart when requested through the openCart query parameter', () => {
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
||||||
|
|
||||||
|
queryParamMapState.next(convertToParamMap({ openCart: 'true' }));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(true);
|
||||||
|
expect((fixture.nativeElement as HTMLElement).querySelector('app-cart')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it('hides the configured header elements when the tenant disables them', () => {
|
it('hides the configured header elements when the tenant disables them', () => {
|
||||||
tenantState.set({
|
tenantState.set({
|
||||||
...tenant,
|
...tenant,
|
||||||
@@ -267,6 +301,12 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(compiled.querySelector('.fa-whatsapp')).not.toBeNull();
|
expect(compiled.querySelector('.fa-whatsapp')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-facebook')).not.toBeNull();
|
expect(compiled.querySelector('.fa-facebook')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull();
|
expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull();
|
||||||
|
expect(compiled.querySelector('.store-layout__contact-details')?.textContent).toContain(
|
||||||
|
tenant.address,
|
||||||
|
);
|
||||||
|
expect(compiled.querySelector('.store-layout__contact-details')?.textContent).toContain(
|
||||||
|
tenant.phone,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('navigates to search results when the search button is clicked', () => {
|
it('navigates to search results when the search button is clicked', () => {
|
||||||
@@ -647,7 +687,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 +725,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();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Component, computed, inject, OnInit, signal } from '@angular/core';
|
import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
|
||||||
import { Router, RouterOutlet } from '@angular/router';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
|
import { ActivatedRoute, Router, RouterOutlet } from '@angular/router';
|
||||||
import { TenantService } from '../../services/tenant.service';
|
import { TenantService } from '../../services/tenant.service';
|
||||||
import { CartService } from '../../services/cart/cart.service';
|
import { CartService } from '../../services/cart/cart.service';
|
||||||
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
|
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
|
||||||
@@ -32,12 +33,24 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
private readonly toastService = inject(ToastService);
|
private readonly toastService = inject(ToastService);
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
protected readonly isCartOpen = signal(false);
|
protected readonly isCartOpen = signal(false);
|
||||||
protected readonly isCreatingPurchase = signal(false);
|
protected readonly isCreatingPurchase = signal(false);
|
||||||
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
|
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
|
||||||
protected readonly 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 +105,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,6 +149,12 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
|
this.route.queryParamMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
|
||||||
|
if (params.get('openCart') === 'true') {
|
||||||
|
this.isCartOpen.set(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
this.cartService.loadCart().subscribe({
|
this.cartService.loadCart().subscribe({
|
||||||
error: (err) => console.error('Error loading cart', err),
|
error: (err) => console.error('Error loading cart', err),
|
||||||
});
|
});
|
||||||
@@ -167,8 +187,8 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
protected async onLogoutClick(): Promise<void> {
|
protected async onLogoutClick(): Promise<void> {
|
||||||
const isLeavingCheckout = this.router.url.startsWith('/checkout');
|
const isLeavingCheckout = this.router.url.startsWith('/checkout');
|
||||||
|
|
||||||
// Checkout must be left while the authenticated session is still valid so
|
// Leave checkout before closing the authenticated session so its component
|
||||||
// its CanDeactivate guard can cancel the pending purchase.
|
// can stop payment polling cleanly. The checkout itself remains pending.
|
||||||
if (isLeavingCheckout) {
|
if (isLeavingCheckout) {
|
||||||
const navigationSucceeded = await this.router.navigate(['/']);
|
const navigationSucceeded = await this.router.navigate(['/']);
|
||||||
|
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ export interface CatalogItemVariant {
|
|||||||
event_date_id?: number | null;
|
event_date_id?: number | null;
|
||||||
event_date_ids?: number[];
|
event_date_ids?: number[];
|
||||||
event_dates?: string[];
|
event_dates?: string[];
|
||||||
stock_tecnico: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
minimum_use_date?: string | null;
|
minimum_use_date?: string | null;
|
||||||
maximum_use_date?: string | null;
|
maximum_use_date?: string | null;
|
||||||
effective_minimum_use_date?: string | null;
|
effective_minimum_use_date?: string | null;
|
||||||
@@ -98,7 +98,7 @@ export interface CatalogItemDetail {
|
|||||||
attributes: ProductAttribute[];
|
attributes: ProductAttribute[];
|
||||||
variants: CatalogItemVariant[];
|
variants: CatalogItemVariant[];
|
||||||
selected_variant?: SelectedCatalogItemVariant;
|
selected_variant?: SelectedCatalogItemVariant;
|
||||||
stock_tecnico?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
images?: string[];
|
images?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,7 +113,7 @@ export interface CatalogFeaturedItemVariant {
|
|||||||
id: number;
|
id: number;
|
||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string;
|
precio?: string;
|
||||||
stock_tecnico: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
values: Record<string, CatalogVariantValue>;
|
values: Record<string, CatalogVariantValue>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,7 +145,7 @@ export interface CatalogFeaturedItem {
|
|||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio: number | string;
|
precio: number | string;
|
||||||
image?: string | null;
|
image?: string | null;
|
||||||
stock_tecnico?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
variants?: CatalogFeaturedItemVariant[];
|
variants?: CatalogFeaturedItemVariant[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,6 +155,7 @@ export type CatalogFeaturedItems =
|
|||||||
|
|
||||||
export interface CatalogFeaturedGroup {
|
export interface CatalogFeaturedGroup {
|
||||||
id: number;
|
id: number;
|
||||||
|
code: string;
|
||||||
title: string;
|
title: string;
|
||||||
layout: CatalogProductLayout;
|
layout: CatalogProductLayout;
|
||||||
group_layout: CatalogGroupLayout;
|
group_layout: CatalogGroupLayout;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { firstValueFrom } from 'rxjs';
|
|||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
import { BaseApiService } from './base-api.service';
|
import { BaseApiService } from './base-api.service';
|
||||||
|
import { CartItemVariant } from './cart/cart.interface';
|
||||||
|
|
||||||
export interface UpdatePurchaseCustomerPayload {
|
export interface UpdatePurchaseCustomerPayload {
|
||||||
dni: string;
|
dni: string;
|
||||||
@@ -73,6 +74,7 @@ export interface PurchaseDetailItemResponse {
|
|||||||
line_total: string;
|
line_total: string;
|
||||||
source_catalog_item_id: number | null;
|
source_catalog_item_id: number | null;
|
||||||
source_variant_id: number | null;
|
source_variant_id: number | null;
|
||||||
|
variants?: CartItemVariant[];
|
||||||
item_details: {
|
item_details: {
|
||||||
nombre: string;
|
nombre: string;
|
||||||
descripcion: string | null;
|
descripcion: string | null;
|
||||||
@@ -95,7 +97,7 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
|||||||
telefono: string | null;
|
telefono: string | null;
|
||||||
nombre_apellido: string | null;
|
nombre_apellido: string | null;
|
||||||
email: string | null;
|
email: string | null;
|
||||||
items_source: 'purchase';
|
items_source: 'purchase' | 'cart';
|
||||||
items: PurchaseDetailItemResponse[];
|
items: PurchaseDetailItemResponse[];
|
||||||
tickets_count?: number;
|
tickets_count?: number;
|
||||||
has_generated_tickets?: boolean;
|
has_generated_tickets?: boolean;
|
||||||
@@ -174,7 +176,20 @@ export class CheckoutService extends BaseApiService {
|
|||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
itemId: number,
|
itemId: number,
|
||||||
quantity: number,
|
quantity: number,
|
||||||
|
cartId: number | null = null,
|
||||||
|
itemsSource: 'purchase' | 'cart' = 'purchase',
|
||||||
): Promise<PurchaseDetailResponse> {
|
): Promise<PurchaseDetailResponse> {
|
||||||
|
if (itemsSource === 'cart' && cartId !== null) {
|
||||||
|
await firstValueFrom(
|
||||||
|
this.http.patch(
|
||||||
|
`${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`,
|
||||||
|
{ cantidad: quantity },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.getPurchase(tenantCode, purchaseId);
|
||||||
|
}
|
||||||
|
|
||||||
const response = await firstValueFrom(
|
const response = await firstValueFrom(
|
||||||
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
|
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
|
||||||
@@ -190,6 +205,51 @@ export class CheckoutService extends BaseApiService {
|
|||||||
return purchase;
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateItemVariant(
|
||||||
|
tenantCode: string,
|
||||||
|
purchaseId: number,
|
||||||
|
itemId: number,
|
||||||
|
variantId: number,
|
||||||
|
quantity: number,
|
||||||
|
cartId: number | null = null,
|
||||||
|
itemsSource: 'purchase' | 'cart' = 'purchase',
|
||||||
|
): Promise<PurchaseDetailResponse> {
|
||||||
|
if (itemsSource === 'cart' && cartId !== null) {
|
||||||
|
await firstValueFrom(
|
||||||
|
this.http.patch(
|
||||||
|
`${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`,
|
||||||
|
{ cantidad: quantity, variant_id: variantId },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await firstValueFrom(
|
||||||
|
this.http.patch(
|
||||||
|
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
|
||||||
|
{ quantity, variant_id: variantId },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.getPurchase(tenantCode, purchaseId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeItem(
|
||||||
|
tenantCode: string,
|
||||||
|
purchaseId: number,
|
||||||
|
itemId: number,
|
||||||
|
cartId: number | null = null,
|
||||||
|
itemsSource: 'purchase' | 'cart' = 'purchase',
|
||||||
|
): Promise<PurchaseDetailResponse> {
|
||||||
|
const url =
|
||||||
|
itemsSource === 'cart' && cartId !== null
|
||||||
|
? `${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`
|
||||||
|
: `${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`;
|
||||||
|
|
||||||
|
await firstValueFrom(this.http.delete(url));
|
||||||
|
|
||||||
|
return this.getPurchase(tenantCode, purchaseId);
|
||||||
|
}
|
||||||
|
|
||||||
async prepareItemEditing(
|
async prepareItemEditing(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
|
|||||||
@@ -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[];
|
||||||
|
|||||||
@@ -232,7 +232,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1001,
|
id: 1001,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -243,7 +243,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1002,
|
id: 1002,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -254,7 +254,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1003,
|
id: 1003,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('c', 'Sector C'),
|
sector: ticketOption('c', 'Sector C'),
|
||||||
@@ -265,7 +265,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1004,
|
id: 1004,
|
||||||
precio: 200000,
|
precio: 200000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -276,7 +276,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1005,
|
id: 1005,
|
||||||
precio: 200000,
|
precio: 200000,
|
||||||
stock_tecnico: 0,
|
maximum_addable_quantity: 0,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -287,7 +287,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1006,
|
id: 1006,
|
||||||
precio: 100000,
|
precio: 100000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('b', 'Sector B'),
|
sector: ticketOption('b', 'Sector B'),
|
||||||
@@ -298,7 +298,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1007,
|
id: 1007,
|
||||||
precio: 100000,
|
precio: 100000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('b', 'Sector B'),
|
sector: ticketOption('b', 'Sector B'),
|
||||||
@@ -309,7 +309,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1008,
|
id: 1008,
|
||||||
precio: 90000,
|
precio: 90000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
@@ -320,7 +320,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1009,
|
id: 1009,
|
||||||
precio: 65000,
|
precio: 65000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
@@ -331,7 +331,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1010,
|
id: 1010,
|
||||||
precio: 40000,
|
precio: 40000,
|
||||||
stock_tecnico: 1,
|
maximum_addable_quantity: 1,
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
stock_tecnico: null,
|
maximum_addable_quantity: null,
|
||||||
values: { size: 'S' },
|
values: { size: 'S' },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -51,12 +51,12 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
stock_tecnico: 0,
|
maximum_addable_quantity: 0,
|
||||||
values: { size: 'S' },
|
values: { size: 'S' },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
stock_tecnico: 2,
|
maximum_addable_quantity: 2,
|
||||||
values: { size: 'M' },
|
values: { size: 'M' },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -92,9 +92,9 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
]);
|
]);
|
||||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{ id: 1, stock_tecnico: null, values: { event_date: '1' } },
|
{ id: 1, maximum_addable_quantity: null, values: { event_date: '1' } },
|
||||||
{ id: 2, stock_tecnico: null, values: { event_date: '2' } },
|
{ id: 2, maximum_addable_quantity: null, values: { event_date: '2' } },
|
||||||
{ id: 3, stock_tecnico: null, values: { event_date: ['1', '2'] } },
|
{ id: 3, maximum_addable_quantity: null, values: { event_date: ['1', '2'] } },
|
||||||
]);
|
]);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
@@ -135,8 +135,8 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
]);
|
]);
|
||||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{ id: 1, stock_tecnico: null, values: { size: 'S', internal_type: 'adult' } },
|
{ id: 1, maximum_addable_quantity: null, values: { size: 'S', internal_type: 'adult' } },
|
||||||
{ id: 2, stock_tecnico: null, values: { size: 'M', internal_type: 'child' } },
|
{ id: 2, maximum_addable_quantity: null, values: { size: 'M', internal_type: 'child' } },
|
||||||
]);
|
]);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
|||||||
@@ -227,7 +227,7 @@ export class ProductAttributeSelectorComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
||||||
return this.inventoryPolicy() === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
|
return variant.maximum_addable_quantity !== 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
private findFirstHexValue(value: unknown): string | null {
|
private findFirstHexValue(value: unknown): string | null {
|
||||||
|
|||||||
@@ -58,17 +58,23 @@
|
|||||||
[subtotal]="cartSubtotal()"
|
[subtotal]="cartSubtotal()"
|
||||||
[discount]="cartDiscount()"
|
[discount]="cartDiscount()"
|
||||||
[total]="cartTotal()"
|
[total]="cartTotal()"
|
||||||
[readonly]="!cartEditingEnabled()"
|
[readonly]="!canModifyCart()"
|
||||||
[allowEditing]="
|
[allowModify]="true"
|
||||||
createdPurchase()?.status === 'created' || createdPurchase()?.status === 'pending_payment'
|
[showModifyWhenReadonly]="true"
|
||||||
"
|
[allowUpdateQuantity]="canUpdateCartQuantity()"
|
||||||
[allowRemove]="false"
|
[allowUpdateVariant]="canUpdateCartVariant()"
|
||||||
|
[requireEditingMode]="true"
|
||||||
|
[allowDelete]="canDeleteCartItems()"
|
||||||
[persistQuantityChanges]="false"
|
[persistQuantityChanges]="false"
|
||||||
|
[persistVariantChanges]="false"
|
||||||
|
[persistDeleteChanges]="false"
|
||||||
[editing]="isEditingItems()"
|
[editing]="isEditingItems()"
|
||||||
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"
|
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"
|
||||||
backgroundColor="transparent"
|
backgroundColor="transparent"
|
||||||
(editingChange)="onEditingItemsChange($event)"
|
(editingChange)="onEditingItemsChange($event)"
|
||||||
(itemQuantityChange)="onPurchaseItemQuantityChange($event)"
|
(itemQuantityChange)="onPurchaseItemQuantityChange($event)"
|
||||||
|
(itemVariantChange)="onPurchaseItemVariantChange($event)"
|
||||||
|
(itemRemove)="onPurchaseItemRemove($event)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { CartService } from '../../../../core/services/cart/cart.service';
|
|||||||
import { CheckoutService } from '../../../../core/services/checkout.service';
|
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
|
import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
|
||||||
import { CheckoutPageComponent } from './checkout-page.component';
|
import { CheckoutPageComponent } from './checkout-page.component';
|
||||||
|
|
||||||
describe('CheckoutPageComponent payment validation', () => {
|
describe('CheckoutPageComponent payment validation', () => {
|
||||||
@@ -17,9 +18,12 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
startCheckout: ReturnType<typeof vi.fn>;
|
startCheckout: ReturnType<typeof vi.fn>;
|
||||||
updateCustomerData: ReturnType<typeof vi.fn>;
|
updateCustomerData: ReturnType<typeof vi.fn>;
|
||||||
updateItemQuantity: ReturnType<typeof vi.fn>;
|
updateItemQuantity: ReturnType<typeof vi.fn>;
|
||||||
|
updateItemVariant: ReturnType<typeof vi.fn>;
|
||||||
|
removeItem: ReturnType<typeof vi.fn>;
|
||||||
prepareItemEditing: ReturnType<typeof vi.fn>;
|
prepareItemEditing: ReturnType<typeof vi.fn>;
|
||||||
cancelPurchase: ReturnType<typeof vi.fn>;
|
cancelPurchase: ReturnType<typeof vi.fn>;
|
||||||
generatePaymentIntent: ReturnType<typeof vi.fn>;
|
generatePaymentIntent: ReturnType<typeof vi.fn>;
|
||||||
|
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>;
|
||||||
};
|
};
|
||||||
@@ -32,7 +36,12 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
let routerStub: { navigate: ReturnType<typeof vi.fn> };
|
let routerStub: { navigate: ReturnType<typeof vi.fn> };
|
||||||
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
|
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
|
||||||
let authUserState: ReturnType<typeof signal>;
|
let authUserState: ReturnType<typeof signal>;
|
||||||
let tenantState: ReturnType<typeof signal<{ codigo: string; cart_editing_enabled?: boolean }>>;
|
let tenantState: ReturnType<
|
||||||
|
typeof signal<{
|
||||||
|
codigo: string;
|
||||||
|
checkout_editing_policy?: CartEditingPolicy;
|
||||||
|
}>
|
||||||
|
>;
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
try {
|
try {
|
||||||
@@ -54,11 +63,14 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
}),
|
}),
|
||||||
updateCustomerData: vi.fn(),
|
updateCustomerData: vi.fn(),
|
||||||
updateItemQuantity: vi.fn(),
|
updateItemQuantity: vi.fn(),
|
||||||
|
updateItemVariant: vi.fn(),
|
||||||
|
removeItem: vi.fn(),
|
||||||
prepareItemEditing: vi.fn(),
|
prepareItemEditing: vi.fn(),
|
||||||
cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }),
|
cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }),
|
||||||
generatePaymentIntent: vi.fn().mockResolvedValue({
|
generatePaymentIntent: vi.fn().mockResolvedValue({
|
||||||
qr_data: { qr_code: 'qr-value' },
|
qr_data: { qr_code: 'qr-value' },
|
||||||
}),
|
}),
|
||||||
|
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||||
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||||
withCustomLoading: vi.fn(),
|
withCustomLoading: vi.fn(),
|
||||||
};
|
};
|
||||||
@@ -87,7 +99,16 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
routerStub = { navigate: vi.fn() };
|
routerStub = { navigate: vi.fn() };
|
||||||
routeQueryParamMap = convertToParamMap({});
|
routeQueryParamMap = 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],
|
||||||
@@ -194,19 +215,28 @@ 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(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
||||||
|
await vi.advanceTimersByTimeAsync(3_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(attempt);
|
||||||
|
expect(component.transferValidationStatus()).toBe('checking');
|
||||||
|
}
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(3_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(30_000);
|
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('navigates after a transfer is confirmed as paid', async () => {
|
it('navigates after a transfer is confirmed as paid', async () => {
|
||||||
@@ -215,25 +245,59 @@ 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(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(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 payment method changes or the component is destroyed', async () => {
|
||||||
|
const first = createComponent();
|
||||||
|
first.component.selectedPaymentMethod.set('transfer');
|
||||||
|
first.component.onComplete();
|
||||||
|
checkoutServiceStub.generatePaymentIntent.mockResolvedValueOnce({});
|
||||||
|
await first.component.selectPaymentMethod('qr');
|
||||||
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
const second = createComponent();
|
||||||
|
second.component.selectedPaymentMethod.set('transfer');
|
||||||
|
second.component.onComplete();
|
||||||
|
second.fixture.destroy();
|
||||||
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('loads purchase items but prefills customer data from the user', async () => {
|
it('loads purchase items but prefills customer data from the user', async () => {
|
||||||
const purchase = {
|
const purchase = {
|
||||||
id: 25,
|
id: 25,
|
||||||
@@ -433,7 +497,14 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
quantity: 3,
|
quantity: 3,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith('tenant-test', 25, 91, 3);
|
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith(
|
||||||
|
'tenant-test',
|
||||||
|
25,
|
||||||
|
91,
|
||||||
|
3,
|
||||||
|
null,
|
||||||
|
'purchase',
|
||||||
|
);
|
||||||
expect(component.createdPurchase()).toBe(updatedPurchase);
|
expect(component.createdPurchase()).toBe(updatedPurchase);
|
||||||
expect(component.isUpdatingItem()).toBe(false);
|
expect(component.isUpdatingItem()).toBe(false);
|
||||||
});
|
});
|
||||||
@@ -466,15 +537,58 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(component.isEditingItems()).toBe(false);
|
expect(component.isEditingItems()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('does not allow item editing when the tenant disables cart editing', async () => {
|
it('shows Modificar and returns to the home cart when checkout editing is disabled', async () => {
|
||||||
tenantState.set({ codigo: 'tenant-test', cart_editing_enabled: false });
|
tenantState.set({
|
||||||
const { component } = createComponent();
|
codigo: 'tenant-test',
|
||||||
|
checkout_editing_policy: {
|
||||||
|
code: 'disabled',
|
||||||
|
allow_modify: false,
|
||||||
|
allow_delete: false,
|
||||||
|
allow_update_quantity: false,
|
||||||
|
allow_update_variant: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const { fixture, component } = createComponent();
|
||||||
|
component.createdPurchase.set({
|
||||||
|
id: 25,
|
||||||
|
status: 'created',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: 91,
|
||||||
|
quantity: 2,
|
||||||
|
unit_price: '100.00',
|
||||||
|
line_total: '200.00',
|
||||||
|
source_catalog_item_id: 8,
|
||||||
|
source_variant_id: null,
|
||||||
|
item_details: {
|
||||||
|
nombre: 'Remera',
|
||||||
|
descripcion: null,
|
||||||
|
slug: 'remera',
|
||||||
|
imagen: null,
|
||||||
|
attributes: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
subtotal: '200.00',
|
||||||
|
total: '200.00',
|
||||||
|
});
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const modifyButton = (fixture.nativeElement as HTMLElement).querySelector('.cart-edit-btn');
|
||||||
|
expect(modifyButton?.textContent?.trim()).toBe('Modificar');
|
||||||
|
expect(
|
||||||
|
(fixture.nativeElement as HTMLElement).querySelector('app-quantity-selector'),
|
||||||
|
).toBeNull();
|
||||||
|
|
||||||
await component.onEditingItemsChange(true);
|
await component.onEditingItemsChange(true);
|
||||||
|
|
||||||
expect(component.cartEditingEnabled()).toBe(false);
|
expect(component.canUpdateCartQuantity()).toBe(false);
|
||||||
|
expect(component.canModifyCart()).toBe(false);
|
||||||
expect(component.isEditingItems()).toBe(false);
|
expect(component.isEditingItems()).toBe(false);
|
||||||
expect(checkoutServiceStub.prepareItemEditing).not.toHaveBeenCalled();
|
expect(checkoutServiceStub.prepareItemEditing).not.toHaveBeenCalled();
|
||||||
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/'], {
|
||||||
|
queryParams: { openCart: true },
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('updates customer data on the existing purchase before payment', async () => {
|
it('updates customer data on the existing purchase before payment', async () => {
|
||||||
@@ -511,14 +625,14 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(component.stepper.next).toHaveBeenCalledOnce();
|
expect(component.stepper.next).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('cancels the pending purchase before allowing navigation away', async () => {
|
it('keeps the checkout purchase intact when navigating away', async () => {
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
|
|
||||||
await expect(component.canDeactivate()).resolves.toBe(true);
|
await expect(component.canDeactivate()).resolves.toBe(true);
|
||||||
|
|
||||||
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
expect(checkoutServiceStub.cancelPurchase).not.toHaveBeenCalled();
|
||||||
expect(cartServiceStub.loadCart).toHaveBeenCalled();
|
expect(cartServiceStub.loadCart).toHaveBeenCalled();
|
||||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(component.createdPurchaseId()).toBeNull();
|
expect(component.createdPurchaseId()).toBe(25);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -60,10 +60,15 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
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 = 9;
|
||||||
|
private readonly transferPollingIntervalMs = 3_000;
|
||||||
|
private readonly transferPollingMaxAttempts = 4;
|
||||||
|
|
||||||
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
private qrPollingAttempts = 0;
|
private qrPollingAttempts = 0;
|
||||||
private qrPollingRunId = 0;
|
private qrPollingRunId = 0;
|
||||||
|
private transferPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private transferPollingAttempts = 0;
|
||||||
|
private transferPollingRunId = 0;
|
||||||
private paymentMethodRequestId = 0;
|
private paymentMethodRequestId = 0;
|
||||||
private navigationStarted = false;
|
private navigationStarted = false;
|
||||||
|
|
||||||
@@ -79,8 +84,17 @@ 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 canUpdateCartQuantity = computed(
|
||||||
() => this.tenantService.tenant()?.cart_editing_enabled ?? true,
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_update_quantity ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canUpdateCartVariant = computed(
|
||||||
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_update_variant ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canDeleteCartItems = computed(
|
||||||
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_delete ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canModifyCart = computed(
|
||||||
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_modify ?? false,
|
||||||
);
|
);
|
||||||
|
|
||||||
protected readonly cartSubtotal = computed(() => {
|
protected readonly cartSubtotal = computed(() => {
|
||||||
@@ -158,6 +172,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,6 +188,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
value: attribute.value === null ? '' : String(attribute.value),
|
value: attribute.value === null ? '' : String(attribute.value),
|
||||||
})),
|
})),
|
||||||
quantity: item.quantity,
|
quantity: item.quantity,
|
||||||
|
variantId: item.source_variant_id,
|
||||||
|
variants: item.variants,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,7 +198,10 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (editing && !this.cartEditingEnabled()) {
|
if (editing && !this.canModifyCart()) {
|
||||||
|
await this.router.navigate(['/'], {
|
||||||
|
queryParams: { openCart: true },
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -197,6 +217,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
this.isEditingItems.set(true);
|
this.isEditingItems.set(true);
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
this.qrData.set(null);
|
this.qrData.set(null);
|
||||||
this.qrPaymentStatus.set('idle');
|
this.qrPaymentStatus.set('idle');
|
||||||
this.transferAccount.set(null);
|
this.transferAccount.set(null);
|
||||||
@@ -231,7 +252,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
const itemId = event.item.cartItemId;
|
const itemId = event.item.cartItemId;
|
||||||
|
|
||||||
if (
|
if (
|
||||||
!this.cartEditingEnabled() ||
|
!this.canUpdateCartQuantity() ||
|
||||||
!tenant ||
|
!tenant ||
|
||||||
!purchaseId ||
|
!purchaseId ||
|
||||||
!itemId ||
|
!itemId ||
|
||||||
@@ -248,6 +269,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
purchaseId,
|
purchaseId,
|
||||||
itemId,
|
itemId,
|
||||||
event.quantity,
|
event.quantity,
|
||||||
|
this.createdPurchase()?.cart_id ?? null,
|
||||||
|
this.createdPurchase()?.items_source ?? 'purchase',
|
||||||
);
|
);
|
||||||
this.createdPurchase.set(purchase);
|
this.createdPurchase.set(purchase);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -257,6 +280,79 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected async onPurchaseItemVariantChange(event: {
|
||||||
|
item: CartItemMock;
|
||||||
|
variantId: number;
|
||||||
|
}): Promise<void> {
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
const purchase = this.createdPurchase();
|
||||||
|
const itemId = event.item.cartItemId;
|
||||||
|
|
||||||
|
if (
|
||||||
|
!this.canUpdateCartVariant() ||
|
||||||
|
!tenant ||
|
||||||
|
!purchase ||
|
||||||
|
!itemId ||
|
||||||
|
this.isUpdatingItem() ||
|
||||||
|
!this.isEditingItems()
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isUpdatingItem.set(true);
|
||||||
|
try {
|
||||||
|
this.createdPurchase.set(
|
||||||
|
await this.checkoutService.updateItemVariant(
|
||||||
|
tenant.codigo,
|
||||||
|
purchase.id,
|
||||||
|
itemId,
|
||||||
|
event.variantId,
|
||||||
|
event.item.quantity,
|
||||||
|
purchase.cart_id,
|
||||||
|
purchase.items_source,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to update purchase item variant:', error);
|
||||||
|
} finally {
|
||||||
|
this.isUpdatingItem.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async onPurchaseItemRemove(event: { item: CartItemMock }): Promise<void> {
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
const purchase = this.createdPurchase();
|
||||||
|
const itemId = event.item.cartItemId;
|
||||||
|
|
||||||
|
if (
|
||||||
|
!this.canDeleteCartItems() ||
|
||||||
|
!tenant ||
|
||||||
|
!purchase ||
|
||||||
|
!itemId ||
|
||||||
|
this.isUpdatingItem() ||
|
||||||
|
!this.isEditingItems()
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isUpdatingItem.set(true);
|
||||||
|
try {
|
||||||
|
this.createdPurchase.set(
|
||||||
|
await this.checkoutService.removeItem(
|
||||||
|
tenant.codigo,
|
||||||
|
purchase.id,
|
||||||
|
itemId,
|
||||||
|
purchase.cart_id,
|
||||||
|
purchase.items_source,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to remove purchase item:', 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() || this.isEditingItems()) return;
|
||||||
|
|
||||||
@@ -296,34 +392,21 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
public async canDeactivate(): Promise<boolean> {
|
public async canDeactivate(): Promise<boolean> {
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
|
|
||||||
if (this.navigationStarted) {
|
if (this.navigationStarted) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const purchaseId = this.createdPurchaseId();
|
// The checkout cart remains attached to its purchase. Once the user adds a
|
||||||
const tenant = this.tenantService.tenant();
|
// new item, the cart API creates a separate active cart automatically.
|
||||||
|
|
||||||
if (!purchaseId || !tenant) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
|
|
||||||
this.createdPurchaseId.set(null);
|
|
||||||
this.createdPurchase.set(null);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await firstValueFrom(this.cartService.loadCart());
|
await firstValueFrom(this.cartService.loadCart());
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to restore cart after cancelling checkout:', error);
|
console.error('Failed to load the active cart after leaving checkout:', error);
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to cancel purchase:', error);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
|
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
|
||||||
@@ -332,6 +415,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
this.qrPaymentStatus.set('idle');
|
this.qrPaymentStatus.set('idle');
|
||||||
this.transferValidationStatus.set('idle');
|
this.transferValidationStatus.set('idle');
|
||||||
this.selectedPaymentMethod.set(method);
|
this.selectedPaymentMethod.set(method);
|
||||||
@@ -389,6 +473,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 {
|
||||||
@@ -443,22 +528,94 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.stopTransferPolling();
|
||||||
this.transferValidationStatus.set('checking');
|
this.transferValidationStatus.set('checking');
|
||||||
|
this.transferPollingAttempts = 0;
|
||||||
|
|
||||||
|
const runId = this.transferPollingRunId;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const purchase = await this.checkoutService
|
const purchase = await this.checkoutService
|
||||||
.withCustomLoading()
|
.withCustomLoading()
|
||||||
.getPurchase(tenant.codigo, purchaseId);
|
.submitPurchaseForReview(tenant.codigo, purchaseId);
|
||||||
|
|
||||||
|
if (runId !== this.transferPollingRunId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (purchase.status === 'paid') {
|
if (purchase.status === 'paid') {
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.scheduleTransferPoll(runId);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to submit transfer payment for review:', error);
|
||||||
|
|
||||||
|
if (runId === this.transferPollingRunId) {
|
||||||
this.transferValidationStatus.set('error');
|
this.transferValidationStatus.set('error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleTransferPoll(runId: number): void {
|
||||||
|
this.transferPollingTimeoutId = setTimeout(() => {
|
||||||
|
this.transferPollingTimeoutId = null;
|
||||||
|
void this.checkTransferPayment(runId);
|
||||||
|
}, this.transferPollingIntervalMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async checkTransferPayment(runId: number): Promise<void> {
|
||||||
|
if (runId !== this.transferPollingRunId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const purchaseId = this.createdPurchaseId();
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
|
||||||
|
if (!purchaseId || !tenant || this.selectedPaymentMethod() !== 'transfer') {
|
||||||
|
this.stopTransferPolling();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.transferPollingAttempts += 1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const purchase = await this.checkoutService
|
||||||
|
.withCustomLoading()
|
||||||
|
.getPurchase(tenant.codigo, purchaseId);
|
||||||
|
|
||||||
|
if (runId !== this.transferPollingRunId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (purchase.status === 'paid') {
|
||||||
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to validate transfer payment:', error);
|
console.error('Failed to validate transfer payment:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (runId !== this.transferPollingRunId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.transferPollingAttempts >= this.transferPollingMaxAttempts) {
|
||||||
|
this.stopTransferPolling();
|
||||||
this.transferValidationStatus.set('error');
|
this.transferValidationStatus.set('error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.scheduleTransferPoll(runId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private stopTransferPolling(): void {
|
||||||
|
this.transferPollingRunId += 1;
|
||||||
|
|
||||||
|
if (this.transferPollingTimeoutId !== null) {
|
||||||
|
clearTimeout(this.transferPollingTimeoutId);
|
||||||
|
this.transferPollingTimeoutId = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -572,6 +729,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
this.navigationStarted = true;
|
this.navigationStarted = true;
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
|
|
||||||
void this.router.navigate(['/checkout/status', purchaseId]);
|
void this.router.navigate(['/checkout/status', purchaseId]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
@@ -36,7 +37,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
has_tickets: false,
|
has_tickets: false,
|
||||||
minimum_use_date: null,
|
minimum_use_date: null,
|
||||||
maximum_use_date: null,
|
maximum_use_date: null,
|
||||||
stock_tecnico: 10,
|
maximum_addable_quantity: 10,
|
||||||
attributes: [],
|
attributes: [],
|
||||||
variants: [],
|
variants: [],
|
||||||
};
|
};
|
||||||
@@ -190,10 +191,10 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
const detailProduct: CatalogItemDetail = {
|
const detailProduct: CatalogItemDetail = {
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
images: ['https://example.com/product.png'],
|
images: ['https://example.com/product.png'],
|
||||||
variants: [{ id: 123, stock_tecnico: 10, values: {} }],
|
variants: [{ id: 123, maximum_addable_quantity: 10, values: {} }],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 10,
|
maximum_addable_quantity: 10,
|
||||||
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
|
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -294,10 +295,12 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
variants: [{ id: 123, stock_tecnico: 10, values: { color: 'beige', material: 'Cuero' } }],
|
variants: [
|
||||||
|
{ id: 123, maximum_addable_quantity: 10, values: { color: 'beige', material: 'Cuero' } },
|
||||||
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 10,
|
maximum_addable_quantity: 10,
|
||||||
images: ['https://example.com/variant1.png'],
|
images: ['https://example.com/variant1.png'],
|
||||||
values: {
|
values: {
|
||||||
color: 'beige',
|
color: 'beige',
|
||||||
@@ -334,8 +337,8 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
purpose: 'entry',
|
purpose: 'entry',
|
||||||
has_tickets: true,
|
has_tickets: true,
|
||||||
variants: [
|
variants: [
|
||||||
{ id: 101, event_date_id: 20, stock_tecnico: 10, values: { event_date: '20' } },
|
{ id: 101, event_date_id: 20, maximum_addable_quantity: 10, values: { event_date: '20' } },
|
||||||
{ id: 102, event_date_id: 21, stock_tecnico: 10, values: { event_date: '21' } },
|
{ id: 102, event_date_id: 21, maximum_addable_quantity: 10, values: { event_date: '21' } },
|
||||||
],
|
],
|
||||||
attributes: [
|
attributes: [
|
||||||
{
|
{
|
||||||
@@ -366,7 +369,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 101,
|
id: 101,
|
||||||
event_date_id: 20,
|
event_date_id: 20,
|
||||||
stock_tecnico: 10,
|
maximum_addable_quantity: 10,
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -410,7 +413,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
|
|
||||||
fixture.componentInstance['selectedVariant'].set({
|
fixture.componentInstance['selectedVariant'].set({
|
||||||
id: 1,
|
id: 1,
|
||||||
stock_tecnico: 10,
|
maximum_addable_quantity: 10,
|
||||||
values: {},
|
values: {},
|
||||||
});
|
});
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -493,19 +496,45 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('shows the backend purchase-limit message for a direct checkout', async () => {
|
||||||
|
checkoutServiceStub.startCheckout.mockRejectedValue(
|
||||||
|
new HttpErrorResponse({
|
||||||
|
status: 422,
|
||||||
|
error: {
|
||||||
|
code: 'purchase.limit_exceeded',
|
||||||
|
message: 'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
|
||||||
|
maximum_addable_quantity: 2,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await configureTestingModule();
|
||||||
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
const buyButton = Array.from(fixture.nativeElement.querySelectorAll('app-button button')).find(
|
||||||
|
(button) => button.textContent?.trim() === 'Comprar',
|
||||||
|
) as HTMLButtonElement;
|
||||||
|
|
||||||
|
buyButton.click();
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
|
'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('calls CartService.addItem when variant is selected and Add to Cart is clicked', async () => {
|
it('calls CartService.addItem when variant is selected and Add to Cart is clicked', async () => {
|
||||||
const detailProduct: CatalogItemDetail = {
|
const detailProduct: CatalogItemDetail = {
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
variants: [
|
variants: [
|
||||||
{
|
{
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 5,
|
maximum_addable_quantity: 5,
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 5,
|
maximum_addable_quantity: 5,
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -538,7 +567,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
resolveProduct({
|
resolveProduct({
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
variants: [],
|
variants: [],
|
||||||
stock_tecnico: 4,
|
maximum_addable_quantity: 4,
|
||||||
});
|
});
|
||||||
|
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
@@ -564,13 +593,13 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
variants: [
|
variants: [
|
||||||
{
|
{
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 5,
|
maximum_addable_quantity: 5,
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
stock_tecnico: 5,
|
maximum_addable_quantity: 5,
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -602,7 +631,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
it('allows unlimited variants to increase quantity without a maximum', async () => {
|
it('allows unlimited variants to increase quantity without a maximum', async () => {
|
||||||
const unlimitedVariant = {
|
const unlimitedVariant = {
|
||||||
id: 321,
|
id: 321,
|
||||||
stock_tecnico: null,
|
maximum_addable_quantity: null,
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
@@ -610,7 +639,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
inventory_policy: 'unlimited',
|
inventory_policy: 'unlimited',
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 321,
|
id: 321,
|
||||||
stock_tecnico: null,
|
maximum_addable_quantity: null,
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -634,7 +663,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
it('caps an unlimited variant at the per-user purchase limit', async () => {
|
it('caps an unlimited variant at the per-user purchase limit', async () => {
|
||||||
const unlimitedVariant = {
|
const unlimitedVariant = {
|
||||||
id: 322,
|
id: 322,
|
||||||
stock_tecnico: null,
|
maximum_addable_quantity: 2,
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
@@ -643,7 +672,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
max_units_per_user: 2,
|
max_units_per_user: 2,
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 322,
|
id: 322,
|
||||||
stock_tecnico: null,
|
maximum_addable_quantity: 2,
|
||||||
images: [],
|
images: [],
|
||||||
values: { event_date: '20' },
|
values: { event_date: '20' },
|
||||||
},
|
},
|
||||||
@@ -667,14 +696,14 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
it('disables purchase actions for tracked variants without stock', async () => {
|
it('disables purchase actions for tracked variants without stock', async () => {
|
||||||
const trackedVariant = {
|
const trackedVariant = {
|
||||||
id: 654,
|
id: 654,
|
||||||
stock_tecnico: 0,
|
maximum_addable_quantity: 0,
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 654,
|
id: 654,
|
||||||
stock_tecnico: 0,
|
maximum_addable_quantity: 0,
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -98,27 +98,23 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
const variant = this.selectedVariant();
|
const variant = this.selectedVariant();
|
||||||
if (!prod) return 0;
|
if (!prod) return 0;
|
||||||
|
|
||||||
const stockLimit = variant
|
return variant
|
||||||
? variant.stock_tecnico
|
? (variant.maximum_addable_quantity ?? null)
|
||||||
: prod.variants.length === 0
|
: prod.variants.length === 0
|
||||||
? (prod.stock_tecnico ?? null)
|
? (prod.maximum_addable_quantity ?? null)
|
||||||
: 0;
|
: 0;
|
||||||
const userLimit = prod.max_units_per_user ?? null;
|
|
||||||
|
|
||||||
if (stockLimit === null) return userLimit;
|
|
||||||
if (userLimit === null) return stockLimit;
|
|
||||||
return Math.min(stockLimit, userLimit);
|
|
||||||
});
|
});
|
||||||
protected readonly selectedVariantAvailable = computed(() => {
|
protected readonly selectedVariantAvailable = computed(() => {
|
||||||
const prod = this.product();
|
const prod = this.product();
|
||||||
if (!prod) return false;
|
if (!prod) return false;
|
||||||
|
if (this.selectedVariantMax() === 0) return false;
|
||||||
|
|
||||||
const variant = this.selectedVariant();
|
const variant = this.selectedVariant();
|
||||||
if (variant) return this.isVariantAvailable(variant, prod);
|
if (variant) return this.isVariantAvailable(variant);
|
||||||
if (prod.purpose === 'entry') return false;
|
if (prod.purpose === 'entry') return false;
|
||||||
if (prod.variants.length > 0) return false;
|
if (prod.variants.length > 0) return false;
|
||||||
|
|
||||||
return prod.inventory_policy === 'unlimited' || (prod.stock_tecnico ?? 0) > 0;
|
return this.selectedVariantMax() !== 0;
|
||||||
});
|
});
|
||||||
protected readonly descriptionExpanded = signal(false);
|
protected readonly descriptionExpanded = signal(false);
|
||||||
protected readonly descriptionMaxHeight = signal(0);
|
protected readonly descriptionMaxHeight = signal(0);
|
||||||
@@ -333,14 +329,18 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
this.toastService.danger('No se pudo iniciar la compra directa.');
|
const message =
|
||||||
|
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
||||||
|
? error.error.message
|
||||||
|
: 'No se pudo iniciar la compra directa.';
|
||||||
|
this.toastService.danger(message);
|
||||||
} finally {
|
} finally {
|
||||||
this.creatingDirectPurchase.set(false);
|
this.creatingDirectPurchase.set(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private isVariantAvailable(variant: CatalogItemVariant, product: CatalogItemDetail): boolean {
|
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
||||||
return product.inventory_policy === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
|
return variant.maximum_addable_quantity !== 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected toggleDescription(): void {
|
protected toggleDescription(): void {
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ describe('productDetailResolver', () => {
|
|||||||
has_tickets: false,
|
has_tickets: false,
|
||||||
minimum_use_date: null,
|
minimum_use_date: null,
|
||||||
maximum_use_date: null,
|
maximum_use_date: null,
|
||||||
stock_tecnico: 0,
|
maximum_addable_quantity: 0,
|
||||||
attributes: [],
|
attributes: [],
|
||||||
variants: [],
|
variants: [],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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"
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ app-store-section + app-store-section {
|
|||||||
margin-top: clamp(3rem, 6vw, 5rem);
|
margin-top: clamp(3rem, 6vw, 5rem);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
app-store-section[id] {
|
||||||
|
scroll-margin-top: 8rem;
|
||||||
|
}
|
||||||
|
|
||||||
:host > .store-home__additional-info:not(:first-child) {
|
:host > .store-home__additional-info:not(:first-child) {
|
||||||
margin-top: clamp(3rem, 6vw, 5rem);
|
margin-top: clamp(3rem, 6vw, 5rem);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ function createCatalog(
|
|||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
id: 7,
|
id: 7,
|
||||||
|
code: 'destacados',
|
||||||
title: 'Destacados',
|
title: 'Destacados',
|
||||||
layout: 'column_with_image',
|
layout: 'column_with_image',
|
||||||
group_layout: 'paginated',
|
group_layout: 'paginated',
|
||||||
@@ -149,6 +150,7 @@ describe('StoreHomePageComponent', () => {
|
|||||||
const element = fixture.nativeElement as HTMLElement;
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
|
||||||
expect(catalogServiceStub.getCatalog).not.toHaveBeenCalled();
|
expect(catalogServiceStub.getCatalog).not.toHaveBeenCalled();
|
||||||
|
expect(element.querySelector('app-store-section')?.id).toBe('destacados');
|
||||||
expect(element.querySelector('.store-section__title')?.textContent?.trim()).toBe('Destacados');
|
expect(element.querySelector('.store-section__title')?.textContent?.trim()).toBe('Destacados');
|
||||||
expect(element.querySelectorAll('app-product-column-with-image')).toHaveLength(2);
|
expect(element.querySelectorAll('app-product-column-with-image')).toHaveLength(2);
|
||||||
expect(element.textContent).toContain('Auriculares Bluetooth');
|
expect(element.textContent).toContain('Auriculares Bluetooth');
|
||||||
|
|||||||
@@ -224,6 +224,11 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (error instanceof HttpErrorResponse && typeof error.error?.message === 'string') {
|
||||||
|
this.toastService.danger(error.error.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.toastService.danger('No se pudo iniciar la compra directa.');
|
this.toastService.danger('No se pudo iniciar la compra directa.');
|
||||||
} finally {
|
} finally {
|
||||||
this.creatingDirectPurchase.set(false);
|
this.creatingDirectPurchase.set(false);
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (hasVariantSelectors() && !quantityDisabled()) {
|
@if (hasVariantSelectors() && !variantDisabled()) {
|
||||||
<app-variant-selector
|
<app-variant-selector
|
||||||
class="cart-item-variant-selector"
|
class="cart-item-variant-selector"
|
||||||
[variants]="variants()"
|
[variants]="variants()"
|
||||||
@@ -55,7 +55,7 @@
|
|||||||
(increase)="onIncrease()"
|
(increase)="onIncrease()"
|
||||||
(decrease)="onDecrease()"
|
(decrease)="onDecrease()"
|
||||||
/>
|
/>
|
||||||
@if (!quantityDisabled() && showRemove()) {
|
@if (!removeDisabled() && allowDelete()) {
|
||||||
<app-icon-button variant="trash" class="cart-item-remove-btn" (click)="onRemove()" />
|
<app-icon-button variant="trash" class="cart-item-remove-btn" (click)="onRemove()" />
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -31,7 +31,9 @@ export class CartItemComponent {
|
|||||||
readonly quantity = input<number>(1);
|
readonly quantity = input<number>(1);
|
||||||
readonly readonly = input<boolean>(false);
|
readonly readonly = input<boolean>(false);
|
||||||
readonly quantityDisabled = input<boolean>(false);
|
readonly quantityDisabled = input<boolean>(false);
|
||||||
readonly showRemove = input<boolean>(true);
|
readonly variantDisabled = input<boolean>(false);
|
||||||
|
readonly removeDisabled = input<boolean>(false);
|
||||||
|
readonly allowDelete = input<boolean>(true);
|
||||||
|
|
||||||
readonly quantityChange = output<number>();
|
readonly quantityChange = output<number>();
|
||||||
readonly remove = output<void>();
|
readonly remove = output<void>();
|
||||||
@@ -61,7 +63,7 @@ export class CartItemComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onVariantChange(variant: unknown): void {
|
protected onVariantChange(variant: unknown): void {
|
||||||
if (!this.quantityDisabled() && typeof variant === 'number') {
|
if (!this.variantDisabled() && typeof variant === 'number') {
|
||||||
this.variantChange.emit(variant);
|
this.variantChange.emit(variant);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,17 @@
|
|||||||
<section
|
<section
|
||||||
class="d-flex flex-column h-100 overflow-hidden text-secondary"
|
class="d-flex flex-column overflow-hidden text-secondary cart-shell"
|
||||||
[style.background-color]="backgroundColor()"
|
[style.background-color]="backgroundColor()"
|
||||||
>
|
>
|
||||||
<header class="d-flex align-items-center p-3 justify-content-between bg-transparent cart-header">
|
<header class="d-flex align-items-center p-3 justify-content-between bg-transparent cart-header">
|
||||||
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
|
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
|
||||||
|
|
||||||
<div class="d-flex align-items-center cart-header-actions">
|
<div class="d-flex align-items-center cart-header-actions">
|
||||||
@if (!readonly() && editable() && allowEditing() && items().length > 0) {
|
@if (
|
||||||
|
allowModify() &&
|
||||||
|
(!readonly() || showModifyWhenReadonly()) &&
|
||||||
|
requireEditingMode() &&
|
||||||
|
items().length > 0
|
||||||
|
) {
|
||||||
<button
|
<button
|
||||||
class="btn btn-link p-0 border-0 cart-edit-btn"
|
class="btn btn-link p-0 border-0 cart-edit-btn"
|
||||||
type="button"
|
type="button"
|
||||||
@@ -48,8 +53,22 @@
|
|||||||
[selectedVariant]="getItemVariant(item)"
|
[selectedVariant]="getItemVariant(item)"
|
||||||
[quantity]="getItemQuantity(item)"
|
[quantity]="getItemQuantity(item)"
|
||||||
[readonly]="readonly()"
|
[readonly]="readonly()"
|
||||||
[quantityDisabled]="!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)"
|
||||||
|
|||||||
@@ -1,7 +1,15 @@
|
|||||||
:host {
|
:host {
|
||||||
display: block;
|
display: flex;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
min-height: 0;
|
||||||
|
max-height: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-shell {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-height: 0;
|
||||||
|
max-height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.cart-header {
|
.cart-header {
|
||||||
|
|||||||
@@ -340,7 +340,7 @@ describe('CartComponent', () => {
|
|||||||
quantity: 1,
|
quantity: 1,
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
fixture.componentRef.setInput('allowEditing', true);
|
fixture.componentRef.setInput('requireEditingMode', true);
|
||||||
const editingChange = vi.fn();
|
const editingChange = vi.fn();
|
||||||
fixture.componentInstance.editing.subscribe(editingChange);
|
fixture.componentInstance.editing.subscribe(editingChange);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -408,7 +408,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 +441,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();
|
||||||
|
|||||||
@@ -53,10 +53,15 @@ export class CartComponent {
|
|||||||
readonly total = input<number>(0);
|
readonly total = input<number>(0);
|
||||||
readonly backgroundColor = input<string>('#ffffff');
|
readonly backgroundColor = input<string>('#ffffff');
|
||||||
readonly readonly = input<boolean>(false);
|
readonly readonly = input<boolean>(false);
|
||||||
readonly 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 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);
|
||||||
|
|
||||||
@@ -66,6 +71,12 @@ export class CartComponent {
|
|||||||
index: number;
|
index: number;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
}>();
|
}>();
|
||||||
|
readonly itemVariantChange = output<{
|
||||||
|
item: CartItemMock;
|
||||||
|
index: number;
|
||||||
|
variantId: number;
|
||||||
|
}>();
|
||||||
|
readonly itemRemove = output<{ item: CartItemMock; index: number }>();
|
||||||
|
|
||||||
protected readonly quantityOverrides = signal<Record<number, number>>({});
|
protected readonly quantityOverrides = signal<Record<number, number>>({});
|
||||||
protected readonly variantOverrides = signal<Record<number, number>>({});
|
protected readonly variantOverrides = signal<Record<number, number>>({});
|
||||||
@@ -125,7 +136,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 +181,19 @@ export class CartComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onItemVariantChange(index: number, variantId: number): void {
|
protected onItemVariantChange(index: number, variantId: number): void {
|
||||||
|
if (this.readonly() || !this.allowUpdateVariant() || this.editingDisabled()) return;
|
||||||
|
|
||||||
const item = this.items()[index];
|
const item = this.items()[index];
|
||||||
const cartItemId = item?.cartItemId;
|
const cartItemId = item?.cartItemId;
|
||||||
|
|
||||||
if (!item || !cartItemId || variantId === this.getItemVariant(item)) return;
|
if (!item || !cartItemId || variantId === this.getItemVariant(item)) return;
|
||||||
|
|
||||||
|
this.itemVariantChange.emit({ item, index, variantId });
|
||||||
|
|
||||||
|
if (!this.persistVariantChanges()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.variantOverrides.update((overrides) => ({ ...overrides, [cartItemId]: variantId }));
|
this.variantOverrides.update((overrides) => ({ ...overrides, [cartItemId]: variantId }));
|
||||||
this.cartService
|
this.cartService
|
||||||
.updateItemVariant(cartItemId, this.getItemQuantity(item), variantId)
|
.updateItemVariant(cartItemId, this.getItemQuantity(item), variantId)
|
||||||
@@ -200,6 +219,8 @@ export class CartComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onItemRemove(index: number): void {
|
protected onItemRemove(index: number): void {
|
||||||
|
if (this.readonly() || !this.allowDelete() || this.editingDisabled()) return;
|
||||||
|
|
||||||
const target = this.resolveRemoveTarget(index);
|
const target = this.resolveRemoveTarget(index);
|
||||||
|
|
||||||
if (!target) {
|
if (!target) {
|
||||||
@@ -215,8 +236,15 @@ export class CartComponent {
|
|||||||
})
|
})
|
||||||
.subscribe((confirmed) => {
|
.subscribe((confirmed) => {
|
||||||
if (confirmed) {
|
if (confirmed) {
|
||||||
|
const item = this.items()[index];
|
||||||
|
if (item) {
|
||||||
|
this.itemRemove.emit({ item, index });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.persistDeleteChanges()) {
|
||||||
this.removeItem(target.cartItemId);
|
this.removeItem(target.cartItemId);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,7 +253,7 @@ export class CartComponent {
|
|||||||
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
|
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
|
||||||
|
|
||||||
protected toggleEditing(): void {
|
protected toggleEditing(): void {
|
||||||
if (!this.editable() || this.editingDisabled()) {
|
if (!this.allowModify() || this.editingDisabled()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
[title]="item.nombre"
|
[title]="item.nombre"
|
||||||
[description]="item.descripcion ?? ''"
|
[description]="item.descripcion ?? ''"
|
||||||
[price]="price(item)"
|
[price]="price(item)"
|
||||||
|
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
|
||||||
[variants]="item.variants ?? []"
|
[variants]="item.variants ?? []"
|
||||||
[saving]="savingProductIds().has(item.id)"
|
[saving]="savingProductIds().has(item.id)"
|
||||||
(buy)="emitRowBuy(item, $event)"
|
(buy)="emitRowBuy(item, $event)"
|
||||||
@@ -23,6 +24,7 @@
|
|||||||
[title]="item.nombre"
|
[title]="item.nombre"
|
||||||
[description]="item.descripcion ?? ''"
|
[description]="item.descripcion ?? ''"
|
||||||
[price]="price(item)"
|
[price]="price(item)"
|
||||||
|
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
|
||||||
[variants]="item.variants ?? []"
|
[variants]="item.variants ?? []"
|
||||||
[saving]="savingProductIds().has(item.id)"
|
[saving]="savingProductIds().has(item.id)"
|
||||||
(buy)="emitColumnBuy(item, $event)"
|
(buy)="emitColumnBuy(item, $event)"
|
||||||
|
|||||||
@@ -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' },
|
||||||
|
|||||||
@@ -21,7 +21,11 @@
|
|||||||
[(selectedVariant)]="selectedVariant"
|
[(selectedVariant)]="selectedVariant"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<app-quantity-selector [(quantity)]="quantity"></app-quantity-selector>
|
<app-quantity-selector
|
||||||
|
[(quantity)]="quantity"
|
||||||
|
[max]="effectiveMaximum()"
|
||||||
|
[disabled]="unavailable()"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="product-row-card__price text-primary">
|
<span class="product-row-card__price text-primary">
|
||||||
@@ -31,10 +35,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>
|
||||||
|
|||||||
@@ -1,4 +1,12 @@
|
|||||||
import { ChangeDetectionStrategy, Component, computed, input, model, output } from '@angular/core';
|
import {
|
||||||
|
ChangeDetectionStrategy,
|
||||||
|
Component,
|
||||||
|
computed,
|
||||||
|
effect,
|
||||||
|
input,
|
||||||
|
model,
|
||||||
|
output,
|
||||||
|
} from '@angular/core';
|
||||||
import { ButtonComponent } from '../button/button.component';
|
import { ButtonComponent } from '../button/button.component';
|
||||||
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
||||||
import {
|
import {
|
||||||
@@ -10,7 +18,7 @@ export interface Variant extends VariantSelectorVariant {
|
|||||||
label?: string;
|
label?: string;
|
||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string | number;
|
precio?: string | number;
|
||||||
stock_tecnico?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -26,6 +34,7 @@ export class ProductRowCardComponent {
|
|||||||
readonly title = input<string>('');
|
readonly title = input<string>('');
|
||||||
readonly description = input<string>('');
|
readonly description = input<string>('');
|
||||||
readonly price = input<number>(0);
|
readonly price = input<number>(0);
|
||||||
|
readonly maximumAddableQuantity = input<number | null>(null);
|
||||||
readonly variants = input<Variant[]>([]);
|
readonly variants = input<Variant[]>([]);
|
||||||
readonly saving = input(false);
|
readonly saving = input(false);
|
||||||
|
|
||||||
@@ -48,11 +57,25 @@ export class ProductRowCardComponent {
|
|||||||
|
|
||||||
return Number.isFinite(variantPrice) ? variantPrice : this.price();
|
return Number.isFinite(variantPrice) ? variantPrice : this.price();
|
||||||
});
|
});
|
||||||
|
protected readonly effectiveMaximum = computed(
|
||||||
|
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
|
||||||
|
);
|
||||||
|
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
|
||||||
|
|
||||||
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
const maximum = this.effectiveMaximum();
|
||||||
|
|
||||||
|
if (maximum !== null && maximum > 0 && this.quantity() > maximum) {
|
||||||
|
this.quantity.set(maximum);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
protected onAddToCart(): void {
|
protected onAddToCart(): void {
|
||||||
if (this.saving()) {
|
if (this.saving() || this.unavailable()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,6 +86,8 @@ export class ProductRowCardComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onBuy(): void {
|
protected onBuy(): void {
|
||||||
|
if (this.unavailable()) return;
|
||||||
|
|
||||||
this.buy.emit({
|
this.buy.emit({
|
||||||
quantity: this.quantity(),
|
quantity: this.quantity(),
|
||||||
variant: this.selectedVariant(),
|
variant: this.selectedVariant(),
|
||||||
|
|||||||
@@ -361,7 +361,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,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,13 +11,21 @@
|
|||||||
@if (!hasVariants()) {
|
@if (!hasVariants()) {
|
||||||
<div class="product-vertical-with-cart-card__summary">
|
<div class="product-vertical-with-cart-card__summary">
|
||||||
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
||||||
<app-quantity-selector [(quantity)]="quantity" />
|
<app-quantity-selector
|
||||||
|
[(quantity)]="quantity"
|
||||||
|
[max]="effectiveMaximum()"
|
||||||
|
[disabled]="unavailable()"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
} @else {
|
} @else {
|
||||||
<div class="product-vertical-with-cart-card__variants">
|
<div class="product-vertical-with-cart-card__variants">
|
||||||
<div class="product-vertical-with-cart-card__summary">
|
<div class="product-vertical-with-cart-card__summary">
|
||||||
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
||||||
<app-quantity-selector [(quantity)]="quantity" />
|
<app-quantity-selector
|
||||||
|
[(quantity)]="quantity"
|
||||||
|
[max]="effectiveMaximum()"
|
||||||
|
[disabled]="unavailable()"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="product-vertical-with-cart-card__variant-selectors">
|
<div class="product-vertical-with-cart-card__variant-selectors">
|
||||||
@@ -29,14 +37,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' }}
|
||||||
|
|||||||
@@ -1,4 +1,12 @@
|
|||||||
import { ChangeDetectionStrategy, Component, computed, input, model, output } from '@angular/core';
|
import {
|
||||||
|
ChangeDetectionStrategy,
|
||||||
|
Component,
|
||||||
|
computed,
|
||||||
|
effect,
|
||||||
|
input,
|
||||||
|
model,
|
||||||
|
output,
|
||||||
|
} from '@angular/core';
|
||||||
|
|
||||||
import { ButtonComponent } from '../button/button.component';
|
import { ButtonComponent } from '../button/button.component';
|
||||||
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
||||||
@@ -10,6 +18,7 @@ import {
|
|||||||
export interface VerticalCartVariant extends VariantSelectorVariant {
|
export interface VerticalCartVariant extends VariantSelectorVariant {
|
||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string | number;
|
precio?: string | number;
|
||||||
|
maximum_addable_quantity?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -23,6 +32,7 @@ export class ProductVerticalWithCartCardComponent {
|
|||||||
readonly title = input<string>('');
|
readonly title = input<string>('');
|
||||||
readonly description = input<string>('');
|
readonly description = input<string>('');
|
||||||
readonly price = input<number>(0);
|
readonly price = input<number>(0);
|
||||||
|
readonly maximumAddableQuantity = input<number | null>(null);
|
||||||
readonly variants = input<VerticalCartVariant[]>([]);
|
readonly variants = input<VerticalCartVariant[]>([]);
|
||||||
readonly saving = input(false);
|
readonly saving = input(false);
|
||||||
|
|
||||||
@@ -45,9 +55,23 @@ export class ProductVerticalWithCartCardComponent {
|
|||||||
});
|
});
|
||||||
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||||
protected readonly hasVariants = computed(() => this.variants().length > 0);
|
protected readonly hasVariants = computed(() => this.variants().length > 0);
|
||||||
|
protected readonly effectiveMaximum = computed(
|
||||||
|
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
|
||||||
|
);
|
||||||
|
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
const maximum = this.effectiveMaximum();
|
||||||
|
|
||||||
|
if (maximum !== null && maximum > 0 && this.quantity() > maximum) {
|
||||||
|
this.quantity.set(maximum);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
protected onAddToCart(): void {
|
protected onAddToCart(): void {
|
||||||
if (this.saving()) {
|
if (this.saving() || this.unavailable()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,6 +79,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() });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user