feat(catalog): replace stock_tecnico with maximum_addable_quantity across components and services

This commit is contained in:
2026-08-19 17:00:03 -03:00
parent cc446433f6
commit 5c6a03b10d
15 changed files with 231 additions and 74 deletions

View File

@@ -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[];
} }

View File

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

View File

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

View File

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

View File

@@ -1,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: {},
}, },

View File

@@ -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 {

View File

@@ -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: [],
}; };

View File

@@ -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);

View File

@@ -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)"

View File

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

View File

@@ -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>

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 { 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(),

View File

@@ -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,
}; };
} }

View File

@@ -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' }}

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 { 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() });
} }