Compare commits

...

6 Commits

31 changed files with 439 additions and 109 deletions

View File

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

View File

@@ -29,7 +29,11 @@
[subtotal]="cartSubtotal()"
[discount]="cartDiscount()"
[total]="cartTotal()"
[readonly]="!cartEditingEnabled()"
[readonly]="!canModifyCart()"
[allowModify]="canModifyCart()"
[allowUpdateQuantity]="canUpdateCartQuantity()"
[allowUpdateVariant]="canUpdateCartVariant()"
[allowDelete]="canDeleteCartItems()"
[backgroundColor]="'#ffffff'"
(closed)="isCartOpen.set(false)"
>

View File

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

View File

@@ -32,6 +32,13 @@ const tenant: Tenant = {
footer_logo: 'https://example.com/footer.png',
header_bg_image: 'https://example.com/header-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: [],
menues: [
{
@@ -647,7 +654,16 @@ describe('StoreLayoutComponent', () => {
});
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({
id: 1,
tenant_codigo: tenant.codigo,
@@ -676,4 +692,62 @@ describe('StoreLayoutComponent', () => {
expect(cartItem.componentInstance.readonly()).toBe(true);
expect(cartItem.nativeElement.querySelector('app-quantity-selector')).toBeNull();
});
it('shows variant selectors only for the full cart editing policy', () => {
const variantCart: Cart = {
id: 1,
tenant_codigo: tenant.codigo,
status: 'active',
subtotal: '100.00',
items: [
{
id: 1,
cantidad: 1,
precio_unitario: '100.00',
catalog_item_id: 1,
variant_id: 10,
nombre: 'Producto',
imagen: null,
variant: { id: 10, precio: '100.00', stock_tecnico: 5, values: { talle: 'M' } },
variants: [
{ id: 10, precio: '100.00', stock_tecnico: 5, values: { talle: 'M' } },
{ id: 11, precio: '100.00', stock_tecnico: 5, values: { talle: 'L' } },
],
},
],
};
tenantState.set({
...tenant,
cart_editing_policy: {
code: 'quantity_and_remove',
allow_modify: true,
allow_delete: true,
allow_update_quantity: true,
allow_update_variant: false,
},
});
cartState.set(variantCart);
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
(fixture.componentInstance as any).isCartOpen.set(true);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('app-variant-selector')).toBeNull();
expect(fixture.nativeElement.querySelector('app-quantity-selector')).not.toBeNull();
tenantState.set({
...tenant,
cart_editing_policy: {
code: 'full',
allow_modify: true,
allow_delete: true,
allow_update_quantity: true,
allow_update_variant: true,
},
});
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('app-variant-selector')).not.toBeNull();
});
});

View File

@@ -36,8 +36,18 @@ export class StoreLayoutComponent implements OnInit {
protected readonly isCartOpen = signal(false);
protected readonly isCreatingPurchase = signal(false);
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
protected readonly cartEditingEnabled = computed(
() => this.tenant()?.cart_editing_enabled ?? true,
protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
protected readonly canModifyCart = computed(
() => this.cartEditingPolicy()?.allow_modify ?? false,
);
protected readonly canDeleteCartItems = computed(
() => this.cartEditingPolicy()?.allow_delete ?? false,
);
protected readonly canUpdateCartQuantity = computed(
() => this.cartEditingPolicy()?.allow_update_quantity ?? false,
);
protected readonly canUpdateCartVariant = computed(
() => this.cartEditingPolicy()?.allow_update_variant ?? false,
);
protected readonly cartSubtotal = computed(() => {
@@ -92,6 +102,7 @@ export class StoreLayoutComponent implements OnInit {
attributes,
quantity: item.cantidad,
variantId: item.variant_id,
variants: item.variants,
};
}

View File

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

View File

@@ -66,7 +66,7 @@ export interface CatalogItemVariant {
event_date_id?: number | null;
event_date_ids?: number[];
event_dates?: string[];
stock_tecnico: number | null;
maximum_addable_quantity?: number | null;
minimum_use_date?: string | null;
maximum_use_date?: string | null;
effective_minimum_use_date?: string | null;
@@ -98,7 +98,7 @@ export interface CatalogItemDetail {
attributes: ProductAttribute[];
variants: CatalogItemVariant[];
selected_variant?: SelectedCatalogItemVariant;
stock_tecnico?: number | null;
maximum_addable_quantity?: number | null;
images?: string[];
}
@@ -113,7 +113,7 @@ export interface CatalogFeaturedItemVariant {
id: number;
descripcion?: string | null;
precio?: string;
stock_tecnico: number | null;
maximum_addable_quantity?: number | null;
values: Record<string, CatalogVariantValue>;
}
@@ -145,7 +145,7 @@ export interface CatalogFeaturedItem {
descripcion?: string | null;
precio: number | string;
image?: string | null;
stock_tecnico?: number | null;
maximum_addable_quantity?: number | null;
variants?: CatalogFeaturedItemVariant[];
}

View File

@@ -1,5 +1,15 @@
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 {
id: number;
tenant_code: string;
@@ -127,7 +137,7 @@ export interface Tenant {
display_categories?: boolean;
display_seach_bar?: boolean;
display_cart?: boolean;
cart_editing_enabled?: boolean;
cart_editing_policy?: CartEditingPolicy;
display_cart_item_images?: boolean;
social_media?: SocialMedia[];
menues?: Menu[];

View File

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

View File

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

View File

@@ -227,7 +227,7 @@ export class ProductAttributeSelectorComponent {
}
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 {

View File

@@ -58,11 +58,13 @@
[subtotal]="cartSubtotal()"
[discount]="cartDiscount()"
[total]="cartTotal()"
[readonly]="!cartEditingEnabled()"
[allowEditing]="
[readonly]="!canModifyCart()"
[allowModify]="canModifyCart()"
[allowUpdateQuantity]="canUpdateCartQuantity()"
[requireEditingMode]="
createdPurchase()?.status === 'created' || createdPurchase()?.status === 'pending_payment'
"
[allowRemove]="false"
[allowDelete]="false"
[persistQuantityChanges]="false"
[editing]="isEditingItems()"
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"

View File

@@ -10,6 +10,7 @@ import { CartService } from '../../../../core/services/cart/cart.service';
import { CheckoutService } from '../../../../core/services/checkout.service';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
import { CheckoutPageComponent } from './checkout-page.component';
describe('CheckoutPageComponent payment validation', () => {
@@ -32,7 +33,12 @@ describe('CheckoutPageComponent payment validation', () => {
let routerStub: { navigate: ReturnType<typeof vi.fn> };
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
let authUserState: ReturnType<typeof signal>;
let tenantState: ReturnType<typeof signal<{ codigo: string; cart_editing_enabled?: boolean }>>;
let tenantState: ReturnType<
typeof signal<{
codigo: string;
cart_editing_policy?: CartEditingPolicy;
}>
>;
beforeAll(() => {
try {
@@ -87,7 +93,16 @@ describe('CheckoutPageComponent payment validation', () => {
routerStub = { navigate: vi.fn() };
routeQueryParamMap = convertToParamMap({});
authUserState = signal(null);
tenantState = signal({ codigo: 'tenant-test' });
tenantState = signal({
codigo: 'tenant-test',
cart_editing_policy: {
code: 'full',
allow_modify: true,
allow_delete: true,
allow_update_quantity: true,
allow_update_variant: true,
},
});
await TestBed.configureTestingModule({
imports: [CheckoutPageComponent],
@@ -467,12 +482,22 @@ describe('CheckoutPageComponent payment validation', () => {
});
it('does not allow item editing when the tenant disables cart editing', async () => {
tenantState.set({ codigo: 'tenant-test', cart_editing_enabled: false });
tenantState.set({
codigo: 'tenant-test',
cart_editing_policy: {
code: 'disabled',
allow_modify: false,
allow_delete: false,
allow_update_quantity: false,
allow_update_variant: false,
},
});
const { component } = createComponent();
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(checkoutServiceStub.prepareItemEditing).not.toHaveBeenCalled();
});

View File

@@ -79,8 +79,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
protected readonly isLoadingPurchase = signal(true);
protected readonly checkoutStepIndex = signal(0);
protected readonly cartEditingEnabled = computed(
() => this.tenantService.tenant()?.cart_editing_enabled ?? true,
protected readonly canUpdateCartQuantity = computed(
() => this.tenantService.tenant()?.cart_editing_policy?.allow_update_quantity ?? false,
);
protected readonly canModifyCart = computed(
() => this.tenantService.tenant()?.cart_editing_policy?.allow_modify ?? false,
);
protected readonly cartSubtotal = computed(() => {
@@ -181,7 +184,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return;
}
if (editing && !this.cartEditingEnabled()) {
if (editing && !this.canModifyCart()) {
return;
}
@@ -231,7 +234,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
const itemId = event.item.cartItemId;
if (
!this.cartEditingEnabled() ||
!this.canUpdateCartQuantity() ||
!tenant ||
!purchaseId ||
!itemId ||

View File

@@ -1,5 +1,6 @@
import { TestBed, getTestBed } from '@angular/core/testing';
import { signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { ActivatedRoute, Router } from '@angular/router';
import { By } from '@angular/platform-browser';
@@ -36,7 +37,7 @@ describe('ProductDetailPageComponent', () => {
has_tickets: false,
minimum_use_date: null,
maximum_use_date: null,
stock_tecnico: 10,
maximum_addable_quantity: 10,
attributes: [],
variants: [],
};
@@ -190,10 +191,10 @@ describe('ProductDetailPageComponent', () => {
const detailProduct: CatalogItemDetail = {
...mockProduct,
images: ['https://example.com/product.png'],
variants: [{ id: 123, stock_tecnico: 10, values: {} }],
variants: [{ id: 123, maximum_addable_quantity: 10, values: {} }],
selected_variant: {
id: 123,
stock_tecnico: 10,
maximum_addable_quantity: 10,
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
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: {
id: 123,
stock_tecnico: 10,
maximum_addable_quantity: 10,
images: ['https://example.com/variant1.png'],
values: {
color: 'beige',
@@ -334,8 +337,8 @@ describe('ProductDetailPageComponent', () => {
purpose: 'entry',
has_tickets: true,
variants: [
{ id: 101, event_date_id: 20, stock_tecnico: 10, values: { event_date: '20' } },
{ id: 102, event_date_id: 21, stock_tecnico: 10, values: { event_date: '21' } },
{ id: 101, event_date_id: 20, maximum_addable_quantity: 10, values: { event_date: '20' } },
{ id: 102, event_date_id: 21, maximum_addable_quantity: 10, values: { event_date: '21' } },
],
attributes: [
{
@@ -366,7 +369,7 @@ describe('ProductDetailPageComponent', () => {
selected_variant: {
id: 101,
event_date_id: 20,
stock_tecnico: 10,
maximum_addable_quantity: 10,
images: [],
values: {},
},
@@ -410,7 +413,7 @@ describe('ProductDetailPageComponent', () => {
fixture.componentInstance['selectedVariant'].set({
id: 1,
stock_tecnico: 10,
maximum_addable_quantity: 10,
values: {},
});
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 () => {
const detailProduct: CatalogItemDetail = {
...mockProduct,
variants: [
{
id: 123,
stock_tecnico: 5,
maximum_addable_quantity: 5,
values: {},
},
],
selected_variant: {
id: 123,
stock_tecnico: 5,
maximum_addable_quantity: 5,
images: [],
values: {},
},
@@ -538,7 +567,7 @@ describe('ProductDetailPageComponent', () => {
resolveProduct({
...mockProduct,
variants: [],
stock_tecnico: 4,
maximum_addable_quantity: 4,
});
await configureTestingModule();
@@ -564,13 +593,13 @@ describe('ProductDetailPageComponent', () => {
variants: [
{
id: 123,
stock_tecnico: 5,
maximum_addable_quantity: 5,
values: {},
},
],
selected_variant: {
id: 123,
stock_tecnico: 5,
maximum_addable_quantity: 5,
images: [],
values: {},
},
@@ -602,7 +631,7 @@ describe('ProductDetailPageComponent', () => {
it('allows unlimited variants to increase quantity without a maximum', async () => {
const unlimitedVariant = {
id: 321,
stock_tecnico: null,
maximum_addable_quantity: null,
values: {},
};
resolveProduct({
@@ -610,7 +639,7 @@ describe('ProductDetailPageComponent', () => {
inventory_policy: 'unlimited',
selected_variant: {
id: 321,
stock_tecnico: null,
maximum_addable_quantity: null,
images: [],
values: {},
},
@@ -634,7 +663,7 @@ describe('ProductDetailPageComponent', () => {
it('caps an unlimited variant at the per-user purchase limit', async () => {
const unlimitedVariant = {
id: 322,
stock_tecnico: null,
maximum_addable_quantity: 2,
values: {},
};
resolveProduct({
@@ -643,7 +672,7 @@ describe('ProductDetailPageComponent', () => {
max_units_per_user: 2,
selected_variant: {
id: 322,
stock_tecnico: null,
maximum_addable_quantity: 2,
images: [],
values: { event_date: '20' },
},
@@ -667,14 +696,14 @@ describe('ProductDetailPageComponent', () => {
it('disables purchase actions for tracked variants without stock', async () => {
const trackedVariant = {
id: 654,
stock_tecnico: 0,
maximum_addable_quantity: 0,
values: {},
};
resolveProduct({
...mockProduct,
selected_variant: {
id: 654,
stock_tecnico: 0,
maximum_addable_quantity: 0,
images: [],
values: {},
},

View File

@@ -98,27 +98,23 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
const variant = this.selectedVariant();
if (!prod) return 0;
const stockLimit = variant
? variant.stock_tecnico
return variant
? (variant.maximum_addable_quantity ?? null)
: prod.variants.length === 0
? (prod.stock_tecnico ?? null)
? (prod.maximum_addable_quantity ?? null)
: 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(() => {
const prod = this.product();
if (!prod) return false;
if (this.selectedVariantMax() === 0) return false;
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.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 descriptionMaxHeight = signal(0);
@@ -333,14 +329,18 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
});
} catch (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 {
this.creatingDirectPurchase.set(false);
}
}
private isVariantAvailable(variant: CatalogItemVariant, product: CatalogItemDetail): boolean {
return product.inventory_policy === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
private isVariantAvailable(variant: CatalogItemVariant): boolean {
return variant.maximum_addable_quantity !== 0;
}
protected toggleDescription(): void {

View File

@@ -28,7 +28,7 @@ describe('productDetailResolver', () => {
has_tickets: false,
minimum_use_date: null,
maximum_use_date: null,
stock_tecnico: 0,
maximum_addable_quantity: 0,
attributes: [],
variants: [],
};

View File

@@ -224,6 +224,11 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
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.');
} finally {
this.creatingDirectPurchase.set(false);

View File

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

View File

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

View File

@@ -1,12 +1,12 @@
<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()"
>
<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>
<div class="d-flex align-items-center cart-header-actions">
@if (!readonly() && editable() && allowEditing() && items().length > 0) {
@if (!readonly() && allowModify() && requireEditingMode() && items().length > 0) {
<button
class="btn btn-link p-0 border-0 cart-edit-btn"
type="button"
@@ -48,8 +48,22 @@
[selectedVariant]="getItemVariant(item)"
[quantity]="getItemQuantity(item)"
[readonly]="readonly()"
[quantityDisabled]="!editable() || editingDisabled() || (allowEditing() && !editing())"
[showRemove]="allowRemove()"
[quantityDisabled]="
readonly() ||
!allowUpdateQuantity() ||
editingDisabled() ||
(requireEditingMode() && !editing())
"
[variantDisabled]="
readonly() ||
!allowUpdateVariant() ||
editingDisabled() ||
(requireEditingMode() && !editing())
"
[removeDisabled]="
readonly() || !allowDelete() || editingDisabled() || (requireEditingMode() && !editing())
"
[allowDelete]="allowDelete()"
(quantityChange)="onItemQuantityChange(idx, $event)"
(variantChange)="onItemVariantChange(idx, $event)"
(remove)="onItemRemove(idx)"

View File

@@ -1,7 +1,15 @@
:host {
display: block;
display: flex;
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 {

View File

@@ -340,7 +340,7 @@ describe('CartComponent', () => {
quantity: 1,
},
]);
fixture.componentRef.setInput('allowEditing', true);
fixture.componentRef.setInput('requireEditingMode', true);
const editingChange = vi.fn();
fixture.componentInstance.editing.subscribe(editingChange);
fixture.detectChanges();
@@ -408,7 +408,7 @@ describe('CartComponent', () => {
).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({
imports: [CartComponent],
providers: [
@@ -441,8 +441,9 @@ describe('CartComponent', () => {
quantity: 1,
},
]);
fixture.componentRef.setInput('allowEditing', true);
fixture.componentRef.setInput('editable', false);
fixture.componentRef.setInput('requireEditingMode', true);
fixture.componentRef.setInput('allowModify', false);
fixture.componentRef.setInput('allowUpdateQuantity', false);
const quantityChange = vi.fn();
fixture.componentInstance.itemQuantityChange.subscribe(quantityChange);
fixture.detectChanges();

View File

@@ -53,9 +53,11 @@ export class CartComponent {
readonly total = input<number>(0);
readonly backgroundColor = input<string>('#ffffff');
readonly readonly = input<boolean>(false);
readonly editable = input<boolean>(true);
readonly allowEditing = input<boolean>(false);
readonly allowRemove = input<boolean>(true);
readonly allowUpdateQuantity = input<boolean>(true);
readonly allowModify = input<boolean>(true);
readonly requireEditingMode = input<boolean>(false);
readonly allowUpdateVariant = input<boolean>(true);
readonly allowDelete = input<boolean>(true);
readonly persistQuantityChanges = input<boolean>(true);
readonly editingDisabled = input<boolean>(false);
readonly editing = model<boolean>(false);
@@ -125,7 +127,7 @@ export class CartComponent {
}
protected onItemQuantityChange(index: number, newQuantity: number): void {
if (!this.editable()) {
if (!this.allowUpdateQuantity()) {
return;
}
@@ -170,6 +172,8 @@ export class CartComponent {
}
protected onItemVariantChange(index: number, variantId: number): void {
if (this.readonly() || !this.allowUpdateVariant() || this.editingDisabled()) return;
const item = this.items()[index];
const cartItemId = item?.cartItemId;
@@ -200,6 +204,8 @@ export class CartComponent {
}
protected onItemRemove(index: number): void {
if (this.readonly() || !this.allowDelete() || this.editingDisabled()) return;
const target = this.resolveRemoveTarget(index);
if (!target) {
@@ -225,7 +231,7 @@ export class CartComponent {
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
protected toggleEditing(): void {
if (!this.editable() || this.editingDisabled()) {
if (!this.allowModify() || this.editingDisabled()) {
return;
}

View File

@@ -12,6 +12,7 @@
[title]="item.nombre"
[description]="item.descripcion ?? ''"
[price]="price(item)"
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
[variants]="item.variants ?? []"
[saving]="savingProductIds().has(item.id)"
(buy)="emitRowBuy(item, $event)"
@@ -23,6 +24,7 @@
[title]="item.nombre"
[description]="item.descripcion ?? ''"
[price]="price(item)"
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
[variants]="item.variants ?? []"
[saving]="savingProductIds().has(item.id)"
(buy)="emitColumnBuy(item, $event)"

View File

@@ -193,8 +193,8 @@ describe('ProductListComponent', () => {
const itemWithVariants: ProductListItem = {
...items[0],
variants: [
{ id: 91, stock_tecnico: 3, values: { fecha: '10 de octubre' } },
{ id: 92, stock_tecnico: 4, values: { fecha: '11 de octubre' } },
{ id: 91, maximum_addable_quantity: 3, values: { fecha: '10 de octubre' } },
{ id: 92, maximum_addable_quantity: 4, values: { fecha: '11 de octubre' } },
],
};
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 () => {
const fixture = await render('row');
const pageChangeSpy = vi.fn();
@@ -252,7 +304,7 @@ describe('ProductListComponent', () => {
{
id: 401,
precio: '10000.00',
stock_tecnico: 1,
maximum_addable_quantity: 1,
values: {
tipo: { value: 'vip', label: 'VIP' },
sector: { value: 'a', label: 'Sector A' },
@@ -263,7 +315,7 @@ describe('ProductListComponent', () => {
{
id: 402,
precio: '12000.00',
stock_tecnico: 1,
maximum_addable_quantity: 1,
values: {
tipo: { value: 'vip', label: 'VIP' },
sector: { value: 'a', label: 'Sector A' },

View File

@@ -21,7 +21,11 @@
[(selectedVariant)]="selectedVariant"
/>
<app-quantity-selector [(quantity)]="quantity"></app-quantity-selector>
<app-quantity-selector
[(quantity)]="quantity"
[max]="effectiveMaximum()"
[disabled]="unavailable()"
/>
</div>
<span class="product-row-card__price text-primary">
@@ -31,10 +35,16 @@
<div class="product-row-card__buttons">
<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 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' }}
</app-button>
</div>

View File

@@ -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 { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
import {
@@ -10,7 +18,7 @@ export interface Variant extends VariantSelectorVariant {
label?: string;
descripcion?: string | null;
precio?: string | number;
stock_tecnico?: number | null;
maximum_addable_quantity?: number | null;
}
@Component({
@@ -26,6 +34,7 @@ export class ProductRowCardComponent {
readonly title = input<string>('');
readonly description = input<string>('');
readonly price = input<number>(0);
readonly maximumAddableQuantity = input<number | null>(null);
readonly variants = input<Variant[]>([]);
readonly saving = input(false);
@@ -48,11 +57,25 @@ export class ProductRowCardComponent {
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()));
constructor() {
effect(() => {
const maximum = this.effectiveMaximum();
if (maximum !== null && maximum > 0 && this.quantity() > maximum) {
this.quantity.set(maximum);
}
});
}
protected onAddToCart(): void {
if (this.saving()) {
if (this.saving() || this.unavailable()) {
return;
}
@@ -63,6 +86,8 @@ export class ProductRowCardComponent {
}
protected onBuy(): void {
if (this.unavailable()) return;
this.buy.emit({
quantity: this.quantity(),
variant: this.selectedVariant(),

View File

@@ -361,7 +361,7 @@ export class ProductTicketSelectorComponent {
return {
id: item.variant.id,
precio: item.variant.precio,
stock_tecnico: item.variant.stock_tecnico,
maximum_addable_quantity: item.variant.stock_tecnico,
values: item.variant.values,
};
}

View File

@@ -11,13 +11,21 @@
@if (!hasVariants()) {
<div class="product-vertical-with-cart-card__summary">
<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>
} @else {
<div class="product-vertical-with-cart-card__variants">
<div class="product-vertical-with-cart-card__summary">
<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 class="product-vertical-with-cart-card__variant-selectors">
@@ -29,14 +37,14 @@
<div class="product-vertical-with-cart-card__actions">
<app-button
variant="primary"
[disabled]="hasVariants() && selectedVariant() === null"
[disabled]="unavailable() || (hasVariants() && selectedVariant() === null)"
(click)="onBuy()"
>
Comprar
</app-button>
<app-button
variant="secondary"
[disabled]="saving() || (hasVariants() && selectedVariant() === null)"
[disabled]="saving() || unavailable() || (hasVariants() && selectedVariant() === null)"
(click)="onAddToCart()"
>
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}

View File

@@ -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 { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
@@ -10,6 +18,7 @@ import {
export interface VerticalCartVariant extends VariantSelectorVariant {
descripcion?: string | null;
precio?: string | number;
maximum_addable_quantity?: number | null;
}
@Component({
@@ -23,6 +32,7 @@ export class ProductVerticalWithCartCardComponent {
readonly title = input<string>('');
readonly description = input<string>('');
readonly price = input<number>(0);
readonly maximumAddableQuantity = input<number | null>(null);
readonly variants = input<VerticalCartVariant[]>([]);
readonly saving = input(false);
@@ -45,9 +55,23 @@ export class ProductVerticalWithCartCardComponent {
});
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
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 {
if (this.saving()) {
if (this.saving() || this.unavailable()) {
return;
}
@@ -55,6 +79,8 @@ export class ProductVerticalWithCartCardComponent {
}
protected onBuy(): void {
if (this.unavailable()) return;
this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
}