6 Commits

23 changed files with 538 additions and 158 deletions

View File

@@ -0,0 +1,59 @@
import { describe, expect, it } from 'vitest';
import { CatalogAvailability } from './catalog.interface';
import {
allowsCatalogAction,
combineCatalogAvailability,
createCatalogAvailability,
maximumCatalogQuantity,
} from './catalog-availability';
describe('catalog availability', () => {
it('represents hidden items without irrelevant actions or quantities', () => {
const availability = createCatalogAvailability(0);
expect(availability).toEqual({
state: 'hidden',
reasons: [
{
code: 'out_of_stock',
message: 'Este producto no tiene stock disponible.',
},
],
});
expect(allowsCatalogAction(availability, 'buy_now')).toBe(false);
expect(maximumCatalogQuantity(availability)).toBe(0);
});
it('intersects product and variant actions and quantities', () => {
const product: CatalogAvailability = {
state: 'visible',
maximum_quantity: 3,
allowed_actions: ['select_variant', 'change_quantity'],
reasons: [{ code: 'limited', message: 'Corregí la selección.' }],
};
const variant: CatalogAvailability = {
state: 'visible',
maximum_quantity: 2,
allowed_actions: ['change_quantity', 'add_to_cart'],
reasons: [],
};
expect(combineCatalogAvailability(product, variant)).toEqual({
state: 'visible',
maximum_quantity: 2,
allowed_actions: ['change_quantity'],
reasons: [{ code: 'limited', message: 'Corregí la selección.' }],
});
});
it('lets a hidden decision win composition', () => {
const availability = combineCatalogAvailability(
createCatalogAvailability(5),
createCatalogAvailability(0),
);
expect(availability.state).toBe('hidden');
expect(allowsCatalogAction(availability, 'add_to_cart')).toBe(false);
});
});

View File

@@ -0,0 +1,80 @@
import { CatalogAction, CatalogAvailability } from './catalog.interface';
const ALL_CATALOG_ACTIONS: CatalogAction[] = [
'select_variant',
'change_quantity',
'add_to_cart',
'buy_now',
];
export const AVAILABLE_CATALOG_AVAILABILITY: CatalogAvailability = {
state: 'visible',
maximum_quantity: null,
allowed_actions: ALL_CATALOG_ACTIONS,
reasons: [],
};
export function createCatalogAvailability(maximumQuantity: number | null): CatalogAvailability {
const unavailable = maximumQuantity === 0;
if (unavailable) {
return {
state: 'hidden',
reasons: [
{
code: 'out_of_stock',
message: 'Este producto no tiene stock disponible.',
},
],
};
}
return {
state: 'visible',
maximum_quantity: maximumQuantity,
allowed_actions: [...ALL_CATALOG_ACTIONS],
reasons: [],
};
}
export function primaryAvailabilityMessage(availability: CatalogAvailability): string | null {
return availability.reasons[0]?.message ?? null;
}
export function allowsCatalogAction(
availability: CatalogAvailability,
action: CatalogAction,
): boolean {
return availability.state === 'visible' && availability.allowed_actions.includes(action);
}
export function maximumCatalogQuantity(availability: CatalogAvailability): number | null {
return availability.state === 'visible' ? availability.maximum_quantity : 0;
}
export function combineCatalogAvailability(
product: CatalogAvailability,
variant?: CatalogAvailability | null,
): CatalogAvailability {
if (!variant) return product;
const reasons = [...product.reasons, ...variant.reasons];
if (product.state === 'hidden' || variant.state === 'hidden') {
return { state: 'hidden', reasons };
}
return {
state: 'visible',
maximum_quantity: minimumNullable(product.maximum_quantity, variant.maximum_quantity),
allowed_actions: product.allowed_actions.filter((action) =>
variant.allowed_actions.includes(action),
),
reasons,
};
}
function minimumNullable(left: number | null, right: number | null): number | null {
if (left === null) return right;
if (right === null) return left;
return Math.min(left, right);
}

View File

@@ -49,6 +49,25 @@ export interface ProductAttribute {
export type InventoryPolicy = 'tracked' | 'unlimited';
export interface CatalogRestriction {
code: 'out_of_stock' | 'user_quota_reached' | string;
message: string;
}
export type CatalogAction = 'select_variant' | 'change_quantity' | 'add_to_cart' | 'buy_now';
export type CatalogAvailability =
| {
state: 'hidden';
reasons: CatalogRestriction[];
}
| {
state: 'visible';
maximum_quantity: number | null;
allowed_actions: CatalogAction[];
reasons: CatalogRestriction[];
};
export interface CatalogVariantOption {
value: string;
label: string;
@@ -66,8 +85,7 @@ export interface CatalogItemVariant {
event_date_id?: number | null;
event_date_ids?: number[];
event_dates?: string[];
maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
availability: CatalogAvailability;
minimum_use_date?: string | null;
maximum_use_date?: string | null;
effective_minimum_use_date?: string | null;
@@ -99,7 +117,7 @@ export interface CatalogItemDetail {
attributes: ProductAttribute[];
variants: CatalogItemVariant[];
selected_variant?: SelectedCatalogItemVariant;
maximum_addable_quantity?: number | null;
availability: CatalogAvailability;
images?: string[];
}
@@ -114,8 +132,7 @@ export interface CatalogFeaturedItemVariant {
id: number;
descripcion?: string | null;
precio?: string;
maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
availability: CatalogAvailability;
values: Record<string, CatalogVariantValue>;
}
@@ -147,8 +164,7 @@ export interface CatalogFeaturedItem {
descripcion?: string | null;
precio: number | string;
image?: string | null;
maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
availability: CatalogAvailability;
variants?: CatalogFeaturedItemVariant[];
}

View File

@@ -13,6 +13,7 @@ import { StoreSectionComponent } from '../../../../shared/components/store-secti
import { ModalService } from '../../../../core/services/modal.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service';
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
import { StepComponent } from '../../../../shared/components/stepper/step.component';
import { CarouselComponent } from '../../../../shared/components/carousel/carousel.component';
@@ -232,7 +233,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1001,
precio: 250000,
maximum_addable_quantity: 1,
availability: createCatalogAvailability(1),
values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'),
@@ -243,7 +244,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1002,
precio: 250000,
maximum_addable_quantity: 1,
availability: createCatalogAvailability(1),
values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'),
@@ -254,7 +255,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1003,
precio: 250000,
maximum_addable_quantity: 1,
availability: createCatalogAvailability(1),
values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('c', 'Sector C'),
@@ -265,7 +266,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1004,
precio: 200000,
maximum_addable_quantity: 1,
availability: createCatalogAvailability(1),
values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'),
@@ -276,7 +277,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1005,
precio: 200000,
maximum_addable_quantity: 0,
availability: createCatalogAvailability(0),
values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'),
@@ -287,7 +288,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1006,
precio: 100000,
maximum_addable_quantity: 1,
availability: createCatalogAvailability(1),
values: {
tipo: ticketOption('general', 'General'),
sector: ticketOption('b', 'Sector B'),
@@ -298,7 +299,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1007,
precio: 100000,
maximum_addable_quantity: 1,
availability: createCatalogAvailability(1),
values: {
tipo: ticketOption('general', 'General'),
sector: ticketOption('b', 'Sector B'),
@@ -309,7 +310,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1008,
precio: 90000,
maximum_addable_quantity: 1,
availability: createCatalogAvailability(1),
values: {
tipo: ticketOption('general', 'General'),
sector: ticketOption('d', 'Sector D'),
@@ -320,7 +321,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1009,
precio: 65000,
maximum_addable_quantity: 1,
availability: createCatalogAvailability(1),
values: {
tipo: ticketOption('general', 'General'),
sector: ticketOption('d', 'Sector D'),
@@ -331,7 +332,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1010,
precio: 40000,
maximum_addable_quantity: 1,
availability: createCatalogAvailability(1),
values: {
tipo: ticketOption('general', 'General'),
sector: ticketOption('d', 'Sector D'),

View File

@@ -17,7 +17,7 @@
[attr.aria-label]="option.label"
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
[title]="option.label"
[disabled]="!availableOptions()[attribute.codigo][option.id]"
[disabled]="disabled() || !availableOptions()[attribute.codigo][option.id]"
(click)="selectAttributeOption(attribute, option)"
>
<span class="visually-hidden">{{ option.label }}</span>
@@ -33,7 +33,7 @@
!availableOptions()[attribute.codigo][option.id]
"
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
[disabled]="!availableOptions()[attribute.codigo][option.id]"
[disabled]="disabled() || !availableOptions()[attribute.codigo][option.id]"
(click)="selectAttributeOption(attribute, option)"
>
{{ option.label }}

View File

@@ -2,6 +2,7 @@ import { TestBed } from '@angular/core/testing';
import { beforeEach, describe, expect, it } from 'vitest';
import { ProductAttribute } from '../../../../core/services/catalog/catalog.interface';
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
import { ProductAttributeSelectorComponent } from './product-attribute-selector.component';
describe('ProductAttributeSelectorComponent', () => {
@@ -31,7 +32,7 @@ describe('ProductAttributeSelectorComponent', () => {
fixture.componentRef.setInput('variants', [
{
id: 1,
maximum_addable_quantity: null,
availability: createCatalogAvailability(null),
values: { size: 'S' },
},
]);
@@ -51,12 +52,12 @@ describe('ProductAttributeSelectorComponent', () => {
fixture.componentRef.setInput('variants', [
{
id: 1,
maximum_addable_quantity: 0,
availability: createCatalogAvailability(0),
values: { size: 'S' },
},
{
id: 2,
maximum_addable_quantity: 2,
availability: createCatalogAvailability(2),
values: { size: 'M' },
},
]);
@@ -92,9 +93,9 @@ describe('ProductAttributeSelectorComponent', () => {
]);
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
fixture.componentRef.setInput('variants', [
{ 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'] } },
{ id: 1, availability: createCatalogAvailability(null), values: { event_date: '1' } },
{ id: 2, availability: createCatalogAvailability(null), values: { event_date: '2' } },
{ id: 3, availability: createCatalogAvailability(null), values: { event_date: ['1', '2'] } },
]);
fixture.detectChanges();
@@ -135,8 +136,16 @@ describe('ProductAttributeSelectorComponent', () => {
]);
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
fixture.componentRef.setInput('variants', [
{ id: 1, maximum_addable_quantity: null, values: { size: 'S', internal_type: 'adult' } },
{ id: 2, maximum_addable_quantity: null, values: { size: 'M', internal_type: 'child' } },
{
id: 1,
availability: createCatalogAvailability(null),
values: { size: 'S', internal_type: 'adult' },
},
{
id: 2,
availability: createCatalogAvailability(null),
values: { size: 'M', internal_type: 'child' },
},
]);
fixture.detectChanges();

View File

@@ -15,6 +15,7 @@ import {
ProductAttribute,
ProductAttributeOption,
} from '../../../../core/services/catalog/catalog.interface';
import { allowsCatalogAction } from '../../../../core/services/catalog/catalog-availability';
@Component({
selector: 'app-product-attribute-selector',
@@ -29,6 +30,7 @@ export class ProductAttributeSelectorComponent {
public variants = input<CatalogItemVariant[]>([]);
public selectedVariant = input<CatalogItemVariant | null>(null);
public inventoryPolicy = input.required<InventoryPolicy>();
public disabled = input(false);
public variantChange = output<CatalogItemVariant | null>();
@@ -51,22 +53,15 @@ export class ProductAttributeSelectorComponent {
const optionNormalized = this.normalizeText(option.value || option.label);
const selectedForAttribute = selections[attribute.codigo] ?? [];
if (
!attribute.allow_multi_select &&
selectedForAttribute.length >= 1 &&
!selectedForAttribute.includes(option.id)
) {
availability[attribute.codigo][option.id] = false;
continue;
}
const isAvailable = variants.some((variant) => {
if (!this.isVariantAvailable(variant)) return false;
const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values);
const desiredOptionIds = selectedForAttribute.includes(option.id)
? selectedForAttribute
: [...selectedForAttribute, option.id];
const desiredOptionIds = attribute.allow_multi_select
? selectedForAttribute.includes(option.id)
? selectedForAttribute
: [...selectedForAttribute, option.id]
: [option.id];
const desiredValues = desiredOptionIds
.map((id) => attribute.options.find((candidate) => candidate.id === id))
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
@@ -137,6 +132,8 @@ export class ProductAttributeSelectorComponent {
attribute: ProductAttribute,
option: ProductAttributeOption,
): void {
if (this.disabled()) return;
this.selectedAttributeOptions.update((current) => {
const selected = current[attribute.codigo] ?? [];
const isMultiple = attribute.allow_multi_select ?? false;
@@ -186,7 +183,15 @@ export class ProductAttributeSelectorComponent {
return [];
}
const defaultValues = this.getVariantAttributeValues(attribute, variant.values);
const defaultValues =
attribute.type === 'event_date'
? (
variant.event_date_ids ??
(variant.event_date_id === null || variant.event_date_id === undefined
? []
: [variant.event_date_id])
).map(String)
: this.getVariantAttributeValues(attribute, variant.values);
if (defaultValues.length === 0) {
return [];
}
@@ -215,6 +220,17 @@ export class ProductAttributeSelectorComponent {
}
}
if (attribute.type === 'event_date') {
const variant = this.variants().find((candidate) => candidate.values === variantAttributes);
const eventDateIds =
variant?.event_date_ids ??
(variant?.event_date_id === null || variant?.event_date_id === undefined
? []
: [variant.event_date_id]);
return eventDateIds.map(String);
}
return [];
}
@@ -227,7 +243,7 @@ export class ProductAttributeSelectorComponent {
}
private isVariantAvailable(variant: CatalogItemVariant): boolean {
return variant.maximum_addable_quantity !== 0;
return allowsCatalogAction(variant.availability, 'select_variant');
}
private findFirstHexValue(value: unknown): string | null {

View File

@@ -44,6 +44,7 @@
[variants]="prod.variants"
[selectedVariant]="prod.selected_variant ?? null"
[inventoryPolicy]="prod.inventory_policy"
[disabled]="!allows(prod.availability, 'select_variant')"
(variantChange)="onVariantChange($event)"
/>
</section>
@@ -53,14 +54,22 @@
<section class="product-detail__section">
<div class="product-detail__purchase">
<app-quantity-selector [(quantity)]="quantity" [max]="selectedVariantMax()" />
@if (restrictionMessage(); as message) {
<p class="mb-0 text-danger" role="status">{{ message }}</p>
}
<app-quantity-selector
[(quantity)]="quantity"
[max]="selectedVariantMax()"
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
/>
<div class="product-detail__actions">
<app-button
class="product-detail__cta"
variant="secondary"
type="button"
[disabled]="!selectedVariantAvailable() || variantLoading() || addingToCart()"
[disabled]="!canAddToCart() || variantLoading() || addingToCart()"
(click)="addToCart()"
>
@if (addingToCart()) {
@@ -75,9 +84,7 @@
<app-button
class="product-detail__cta"
type="button"
[disabled]="
!selectedVariantAvailable() || variantLoading() || creatingDirectPurchase()
"
[disabled]="!canBuyNow() || variantLoading() || creatingDirectPurchase()"
(click)="buyNow()"
>
@if (variantLoading() || creatingDirectPurchase()) {

View File

@@ -10,6 +10,7 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
import { CartService } from '../../../../core/services/cart/cart.service';
import { ToastService } from '../../../../core/services/toast.service';
import { ProductDetailPageComponent } from './product-detail-page.component';
@@ -38,7 +39,7 @@ describe('ProductDetailPageComponent', () => {
has_tickets: false,
minimum_use_date: null,
maximum_use_date: null,
maximum_addable_quantity: 10,
availability: createCatalogAvailability(10),
attributes: [],
variants: [],
};
@@ -179,7 +180,7 @@ describe('ProductDetailPageComponent', () => {
it('reloads product availability when the cart changes', async () => {
catalogServiceStub.getCatalogItem.mockReturnValue(
of({ ...mockProduct, maximum_addable_quantity: 4 }),
of({ ...mockProduct, availability: createCatalogAvailability(4) }),
);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
@@ -192,6 +193,21 @@ describe('ProductDetailPageComponent', () => {
expect(fixture.componentInstance['selectedVariantMax']()).toBe(4);
});
it('stops presenting a product that becomes hidden during an availability refresh', async () => {
catalogServiceStub.getCatalogItem.mockReturnValue(
throwError(() => new HttpErrorResponse({ status: 404 })),
);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges();
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
fixture.detectChanges();
expect(fixture.componentInstance['product']()).toBeNull();
expect(fixture.nativeElement.textContent).toContain('Este producto ya no está disponible.');
});
it('shows error message if the resolver cannot load the product', async () => {
resolveProductError(PRODUCT_DETAIL_ERROR_MESSAGE);
await configureTestingModule();
@@ -207,10 +223,10 @@ describe('ProductDetailPageComponent', () => {
const detailProduct: CatalogItemDetail = {
...mockProduct,
images: ['https://example.com/product.png'],
variants: [{ id: 123, maximum_addable_quantity: 10, values: {} }],
variants: [{ id: 123, availability: createCatalogAvailability(10), values: {} }],
selected_variant: {
id: 123,
maximum_addable_quantity: 10,
availability: createCatalogAvailability(10),
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
values: {},
},
@@ -312,11 +328,15 @@ describe('ProductDetailPageComponent', () => {
},
],
variants: [
{ id: 123, maximum_addable_quantity: 10, values: { color: 'beige', material: 'Cuero' } },
{
id: 123,
availability: createCatalogAvailability(10),
values: { color: 'beige', material: 'Cuero' },
},
],
selected_variant: {
id: 123,
maximum_addable_quantity: 10,
availability: createCatalogAvailability(10),
images: ['https://example.com/variant1.png'],
values: {
color: 'beige',
@@ -353,8 +373,18 @@ describe('ProductDetailPageComponent', () => {
purpose: 'entry',
has_tickets: true,
variants: [
{ id: 101, event_date_id: 20, maximum_addable_quantity: 10, values: { event_date: '20' } },
{ id: 102, event_date_id: 21, maximum_addable_quantity: 10, values: { event_date: '21' } },
{
id: 101,
event_date_id: 20,
availability: createCatalogAvailability(10),
values: { event_date: '20' },
},
{
id: 102,
event_date_id: 21,
availability: createCatalogAvailability(10),
values: { event_date: '21' },
},
],
attributes: [
{
@@ -385,7 +415,7 @@ describe('ProductDetailPageComponent', () => {
selected_variant: {
id: 101,
event_date_id: 20,
maximum_addable_quantity: 10,
availability: createCatalogAvailability(10),
images: [],
values: {},
},
@@ -407,6 +437,8 @@ describe('ProductDetailPageComponent', () => {
options[1].click();
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, 102);
});
@@ -429,7 +461,7 @@ describe('ProductDetailPageComponent', () => {
fixture.componentInstance['selectedVariant'].set({
id: 1,
maximum_addable_quantity: 10,
availability: createCatalogAvailability(10),
values: {},
});
fixture.detectChanges();
@@ -519,7 +551,7 @@ describe('ProductDetailPageComponent', () => {
error: {
code: 'purchase.limit_exceeded',
message: 'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
maximum_addable_quantity: 2,
availability: createCatalogAvailability(2),
},
}),
);
@@ -544,13 +576,13 @@ describe('ProductDetailPageComponent', () => {
variants: [
{
id: 123,
maximum_addable_quantity: 5,
availability: createCatalogAvailability(5),
values: {},
},
],
selected_variant: {
id: 123,
maximum_addable_quantity: 5,
availability: createCatalogAvailability(5),
images: [],
values: {},
},
@@ -583,7 +615,7 @@ describe('ProductDetailPageComponent', () => {
resolveProduct({
...mockProduct,
variants: [],
maximum_addable_quantity: 4,
availability: createCatalogAvailability(4),
});
await configureTestingModule();
@@ -609,13 +641,13 @@ describe('ProductDetailPageComponent', () => {
variants: [
{
id: 123,
maximum_addable_quantity: 5,
availability: createCatalogAvailability(5),
values: {},
},
],
selected_variant: {
id: 123,
maximum_addable_quantity: 5,
availability: createCatalogAvailability(5),
images: [],
values: {},
},
@@ -647,7 +679,7 @@ describe('ProductDetailPageComponent', () => {
it('allows unlimited variants to increase quantity without a maximum', async () => {
const unlimitedVariant = {
id: 321,
maximum_addable_quantity: null,
availability: createCatalogAvailability(null),
values: {},
};
resolveProduct({
@@ -655,7 +687,7 @@ describe('ProductDetailPageComponent', () => {
inventory_policy: 'unlimited',
selected_variant: {
id: 321,
maximum_addable_quantity: null,
availability: createCatalogAvailability(null),
images: [],
values: {},
},
@@ -679,7 +711,7 @@ describe('ProductDetailPageComponent', () => {
it('caps an unlimited variant at the per-user purchase limit', async () => {
const unlimitedVariant = {
id: 322,
maximum_addable_quantity: 2,
availability: createCatalogAvailability(2),
values: {},
};
resolveProduct({
@@ -688,7 +720,7 @@ describe('ProductDetailPageComponent', () => {
max_units_per_user: 2,
selected_variant: {
id: 322,
maximum_addable_quantity: 2,
availability: createCatalogAvailability(2),
images: [],
values: { event_date: '20' },
},
@@ -712,14 +744,14 @@ describe('ProductDetailPageComponent', () => {
it('disables purchase actions for tracked variants without stock', async () => {
const trackedVariant = {
id: 654,
maximum_addable_quantity: 0,
availability: createCatalogAvailability(0),
values: {},
};
resolveProduct({
...mockProduct,
selected_variant: {
id: 654,
maximum_addable_quantity: 0,
availability: createCatalogAvailability(0),
images: [],
values: {},
},

View File

@@ -32,6 +32,13 @@ import { ProductDetailResolvedData } from './product-detail-page.resolver';
import { CheckoutService } from '../../../../core/services/checkout.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { AuthService } from '../../../../core/services/auth/auth.service';
import {
AVAILABLE_CATALOG_AVAILABILITY,
allowsCatalogAction,
combineCatalogAvailability,
maximumCatalogQuantity,
primaryAvailabilityMessage,
} from '../../../../core/services/catalog/catalog-availability';
@Component({
selector: 'app-product-detail-page',
@@ -96,29 +103,41 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
() => this.selectedVariant()?.precio ?? this.product()?.precio,
);
protected readonly quantity = signal(1);
protected readonly effectiveAvailability = computed(() => {
const prod = this.product();
const variant = this.selectedVariant();
if (!prod) return AVAILABLE_CATALOG_AVAILABILITY;
return combineCatalogAvailability(prod.availability, variant?.availability);
});
protected readonly selectedVariantMax = computed<number | null>(() => {
const prod = this.product();
const variant = this.selectedVariant();
if (!prod) return 0;
if (!variant && prod.variants.length > 0) return 0;
return variant
? (variant.maximum_addable_quantity ?? null)
: prod.variants.length === 0
? (prod.maximum_addable_quantity ?? null)
: 0;
return maximumCatalogQuantity(this.effectiveAvailability());
});
protected readonly selectedVariantAvailable = computed(() => {
protected readonly hasPurchasableSelection = 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);
if (prod.purpose === 'entry') return false;
if (prod.variants.length > 0) return false;
return this.selectedVariantMax() !== 0;
return prod.variants.length === 0 || this.selectedVariant() !== null;
});
protected readonly canAddToCart = computed(
() =>
this.hasPurchasableSelection() &&
allowsCatalogAction(this.effectiveAvailability(), 'add_to_cart'),
);
protected readonly canBuyNow = computed(
() =>
this.hasPurchasableSelection() &&
allowsCatalogAction(this.effectiveAvailability(), 'buy_now'),
);
protected readonly restrictionMessage = computed(() =>
primaryAvailabilityMessage(this.effectiveAvailability()),
);
protected readonly allows = allowsCatalogAction;
protected readonly descriptionExpanded = signal(false);
protected readonly descriptionMaxHeight = signal(0);
protected readonly descriptionHasOverflow = signal(false);
@@ -224,8 +243,12 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
this.quantity.set(Math.max(1, maximum));
}
},
error: () => {
// Keep the last known availability if the silent refresh fails.
error: (error: HttpErrorResponse) => {
if (error.status === 404) {
this.product.set(null);
this.selectedVariant.set(null);
this.error.set('Este producto ya no está disponible.');
}
},
});
}
@@ -295,8 +318,10 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
protected addToCart(): void {
const currentProduct = this.product();
const variant = this.selectedVariant();
if (!currentProduct || !this.selectedVariantAvailable()) {
this.toastService.danger('Por favor, selecciona una variante.');
if (!currentProduct || !this.canAddToCart()) {
this.toastService.danger(
this.effectiveAvailability().reasons[0]?.message ?? 'Por favor, selecciona una variante.',
);
return;
}
@@ -326,8 +351,10 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
return;
}
if (!currentProduct || !this.selectedVariantAvailable()) {
this.toastService.danger('Por favor, selecciona una variante.');
if (!currentProduct || !this.canBuyNow()) {
this.toastService.danger(
this.effectiveAvailability().reasons[0]?.message ?? 'Por favor, selecciona una variante.',
);
return;
}
@@ -373,10 +400,6 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
}
}
private isVariantAvailable(variant: CatalogItemVariant): boolean {
return variant.maximum_addable_quantity !== 0;
}
protected toggleDescription(): void {
this.descriptionExpanded.update((current) => !current);
}

View File

@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
import {
PRODUCT_DETAIL_ERROR_MESSAGE,
PRODUCT_DETAIL_INVALID_ID_MESSAGE,
@@ -29,7 +30,7 @@ describe('productDetailResolver', () => {
has_tickets: false,
minimum_use_date: null,
maximum_use_date: null,
maximum_addable_quantity: 0,
availability: createCatalogAvailability(0),
attributes: [],
variants: [],
};

View File

@@ -13,6 +13,7 @@ import {
} from '../../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
import { Tenant } from '../../../../core/services/tenant.interface';
import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service';
@@ -83,6 +84,7 @@ const pageOneItems: CatalogFeaturedItem[] = [
nombre: 'Auriculares Bluetooth',
precio: '24999.00',
image: '/catalog/auriculares.jpg',
availability: createCatalogAvailability(null),
},
{
id: 2,
@@ -90,6 +92,7 @@ const pageOneItems: CatalogFeaturedItem[] = [
nombre: 'Teclado Mecanico',
precio: '18999.00',
image: null,
availability: createCatalogAvailability(null),
},
];
@@ -406,7 +409,14 @@ describe('StoreHomePageComponent', () => {
it('requests another page for the selected featured group', async () => {
const pageTwoItems: CatalogFeaturedItem[] = [
{ id: 3, type: 'product', nombre: 'Mouse Gamer', precio: '15999.00', image: null },
{
id: 3,
type: 'product',
nombre: 'Mouse Gamer',
precio: '15999.00',
image: null,
availability: createCatalogAvailability(null),
},
];
const catalogServiceStub = {
getCatalog: vi.fn(),

View File

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

View File

@@ -6,6 +6,7 @@ import { of } from 'rxjs';
import { ApiPaginatedResponse } from '../../../core/services/api-paginated-response.interface';
import { CartService } from '../../../core/services/cart/cart.service';
import { CatalogService } from '../../../core/services/catalog/catalog.service';
import { createCatalogAvailability } from '../../../core/services/catalog/catalog-availability';
import {
CatalogFeaturedItems,
CatalogGroupLayout,
@@ -23,6 +24,7 @@ describe('ProductListComponent', () => {
descripcion: 'Primera descripcion',
precio: '100.00',
image: '/images/one.png',
availability: createCatalogAvailability(null),
variants: [],
},
{
@@ -32,6 +34,7 @@ describe('ProductListComponent', () => {
descripcion: 'Segunda descripcion',
precio: 200,
image: null,
availability: createCatalogAvailability(null),
variants: [],
},
];
@@ -56,6 +59,20 @@ describe('ProductListComponent', () => {
) {
const getVariantOptions = vi.fn().mockReturnValue(
of({
variants: [
{
id: 401,
precio: '10000.00',
availability: createCatalogAvailability(1),
values: { tipo: '1', sector: '2', fila: '3', asiento: '4' },
},
{
id: 402,
precio: '12000.00',
availability: createCatalogAvailability(1),
values: { tipo: '1', sector: '2', fila: '3', asiento: '5' },
},
],
selectors: ['tipo', 'sector', 'fila', 'asiento'].map((key, index) => ({
key,
label: key,
@@ -73,7 +90,12 @@ describe('ProductListComponent', () => {
await TestBed.configureTestingModule({
imports: [ProductListComponent],
providers: [
{ provide: CatalogService, useValue: { getVariantOptions } },
{
provide: CatalogService,
useValue: {
withoutLoading: () => ({ getVariantOptions }),
},
},
{ provide: CartService, useValue: {} },
],
}).compileComponents();
@@ -193,8 +215,8 @@ describe('ProductListComponent', () => {
const itemWithVariants: ProductListItem = {
...items[0],
variants: [
{ id: 91, maximum_addable_quantity: 3, values: { fecha: '10 de octubre' } },
{ id: 92, maximum_addable_quantity: 4, values: { fecha: '11 de octubre' } },
{ id: 91, availability: createCatalogAvailability(3), values: { fecha: '10 de octubre' } },
{ id: 92, availability: createCatalogAvailability(4), values: { fecha: '11 de octubre' } },
],
};
const fixture = await render('column_with_cart', [itemWithVariants]);
@@ -220,7 +242,7 @@ describe('ProductListComponent', () => {
variants: [
{
id: 91,
maximum_addable_quantity: 2,
availability: createCatalogAvailability(2),
values: { fecha: '10 de octubre' },
},
],
@@ -248,7 +270,7 @@ describe('ProductListComponent', () => {
variants: [
{
id: 91,
maximum_addable_quantity: 0,
availability: createCatalogAvailability(0),
values: { fecha: '10 de octubre' },
},
],
@@ -304,7 +326,7 @@ describe('ProductListComponent', () => {
{
id: 401,
precio: '10000.00',
maximum_addable_quantity: 1,
availability: createCatalogAvailability(1),
values: {
tipo: { value: 'vip', label: 'VIP' },
sector: { value: 'a', label: 'Sector A' },
@@ -315,7 +337,7 @@ describe('ProductListComponent', () => {
{
id: 402,
precio: '12000.00',
maximum_addable_quantity: 1,
availability: createCatalogAvailability(1),
values: {
tipo: { value: 'vip', label: 'VIP' },
sector: { value: 'a', label: 'Sector A' },

View File

@@ -18,6 +18,11 @@ import {
CatalogGroupLayout,
CatalogProductLayout,
} from '../../../core/services/catalog/catalog.interface';
import {
AVAILABLE_CATALOG_AVAILABILITY,
allowsCatalogAction,
primaryAvailabilityMessage,
} from '../../../core/services/catalog/catalog-availability';
import { CarouselComponent } from '../carousel/carousel.component';
import { PaginatorComponent } from '../paginator/paginator.component';
import { ProductColumnWithImageComponent } from '../product-column-with-image/product-column-with-image.component';
@@ -74,6 +79,7 @@ export class ProductListComponent {
readonly buy = output<ProductListBuyEvent>();
readonly addToCart = output<ProductListCartEvent>();
readonly pageChange = output<number>();
protected readonly allows = allowsCatalogAction;
protected readonly effectiveLayout = computed<ProductListLayout>(() =>
this.mobile() && this.layout() === 'row' ? 'column_with_cart' : this.layout(),
@@ -108,6 +114,14 @@ export class ProductListComponent {
return Number.isFinite(price) ? price : 0;
}
protected availabilityMessage(item: ProductListItem): string | null {
return primaryAvailabilityMessage(this.itemAvailability(item));
}
protected itemAvailability(item: ProductListItem) {
return item.availability ?? AVAILABLE_CATALOG_AVAILABILITY;
}
protected emitRowCart(
product: ProductListItem,
event: { quantity: number; variant: unknown },

View File

@@ -21,13 +21,14 @@
<app-variant-selector
class="product-row-card__selectors"
[variants]="variants()"
[disabled]="!allows(availability(), 'select_variant')"
[(selectedVariant)]="selectedVariant"
/>
<app-quantity-selector
[(quantity)]="quantity"
[max]="effectiveMaximum()"
[disabled]="unavailable()"
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
/>
</div>
@@ -38,14 +39,22 @@
<div class="product-row-card__buttons">
<div class="product-row-card__btn-wrapper">
<app-button variant="primary" [disabled]="unavailable()" (click)="onBuy()">
<app-button
variant="primary"
[disabled]="!hasPurchasableSelection() || !allows(effectiveAvailability(), 'buy_now')"
(click)="onBuy()"
>
Comprar
</app-button>
</div>
<div class="product-row-card__btn-wrapper">
<app-button
variant="secondary"
[disabled]="saving() || unavailable()"
[disabled]="
saving() ||
!hasPurchasableSelection() ||
!allows(effectiveAvailability(), 'add_to_cart')
"
(click)="onAddToCart()"
>
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}

View File

@@ -14,13 +14,20 @@ import {
VariantSelectorComponent,
VariantSelectorVariant,
} from '../variant-selector/variant-selector.component';
import { CatalogAvailability } from '../../../core/services/catalog/catalog.interface';
import {
AVAILABLE_CATALOG_AVAILABILITY,
allowsCatalogAction,
combineCatalogAvailability,
maximumCatalogQuantity,
primaryAvailabilityMessage,
} from '../../../core/services/catalog/catalog-availability';
export interface Variant extends VariantSelectorVariant {
label?: string;
descripcion?: string | null;
precio?: string | number;
maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
availability?: CatalogAvailability;
}
@Component({
@@ -36,8 +43,7 @@ export class ProductRowCardComponent {
readonly title = input<string>('');
readonly description = input<string>('');
readonly price = input<number>(0);
readonly maximumAddableQuantity = input<number | null>(null);
readonly unavailableMessage = input<string | null>(null);
readonly availability = input<CatalogAvailability>(AVAILABLE_CATALOG_AVAILABILITY);
readonly variants = input<Variant[]>([]);
readonly saving = input(false);
@@ -60,19 +66,22 @@ export class ProductRowCardComponent {
return Number.isFinite(variantPrice) ? variantPrice : this.price();
});
protected readonly effectiveMaximum = computed(
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
protected readonly effectiveAvailability = computed(() =>
combineCatalogAvailability(this.availability(), this.selectedVariantData()?.availability),
);
protected readonly hasVariants = computed(() => this.variants().length > 0);
protected readonly hasPurchasableSelection = computed(
() => !this.hasVariants() || this.selectedVariantData() !== undefined,
);
protected readonly effectiveMaximum = computed(() =>
maximumCatalogQuantity(this.effectiveAvailability()),
);
protected readonly effectiveUnavailableMessage = computed(() =>
primaryAvailabilityMessage(this.effectiveAvailability()),
);
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
protected readonly effectiveUnavailableMessage = computed(() => {
const selectedVariant = this.selectedVariantData();
return selectedVariant
? (selectedVariant.unavailable_message ?? null)
: this.unavailableMessage();
});
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
protected readonly allows = allowsCatalogAction;
constructor() {
effect(() => {
@@ -85,7 +94,11 @@ export class ProductRowCardComponent {
}
protected onAddToCart(): void {
if (this.saving() || this.unavailable()) {
if (
this.saving() ||
!this.hasPurchasableSelection() ||
!this.allows(this.effectiveAvailability(), 'add_to_cart')
) {
return;
}
@@ -96,7 +109,8 @@ export class ProductRowCardComponent {
}
protected onBuy(): void {
if (this.unavailable()) return;
if (!this.hasPurchasableSelection() || !this.allows(this.effectiveAvailability(), 'buy_now'))
return;
this.buy.emit({
quantity: this.quantity(),

View File

@@ -23,6 +23,10 @@ import {
CatalogVariantSelector,
CatalogVariantValue,
} from '../../../core/services/catalog/catalog.interface';
import {
allowsCatalogAction,
createCatalogAvailability,
} from '../../../core/services/catalog/catalog-availability';
import { CatalogService } from '../../../core/services/catalog/catalog.service';
import { ModalService } from '../../../core/services/modal.service';
import { ToastService } from '../../../core/services/toast.service';
@@ -353,7 +357,11 @@ export class ProductTicketSelectorComponent {
if (reservedVariant !== null && !variants.some(({ id }) => id === reservedVariant.id)) {
variants.push(reservedVariant);
}
return variants.filter(({ id }) => !reservedByOtherRows.has(id));
return variants.filter(
({ id, availability }) =>
(availability === undefined || allowsCatalogAction(availability, 'select_variant')) &&
!reservedByOtherRows.has(id),
);
}
private reservedVariantData(row: TicketSelectionRow): CatalogFeaturedItemVariant | null {
@@ -363,7 +371,9 @@ export class ProductTicketSelectorComponent {
return {
id: item.variant.id,
precio: item.variant.precio,
maximum_addable_quantity: item.variant.stock_tecnico,
availability: createCatalogAvailability(
item.variant.stock_tecnico === null ? null : item.variant.stock_tecnico + item.cantidad,
),
values: item.variant.values,
};
}

View File

@@ -19,7 +19,7 @@
<app-quantity-selector
[(quantity)]="quantity"
[max]="effectiveMaximum()"
[disabled]="unavailable()"
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
/>
</div>
} @else {
@@ -29,12 +29,16 @@
<app-quantity-selector
[(quantity)]="quantity"
[max]="effectiveMaximum()"
[disabled]="unavailable()"
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
/>
</div>
<div class="product-vertical-with-cart-card__variant-selectors">
<app-variant-selector [variants]="variants()" [(selectedVariant)]="selectedVariant" />
<app-variant-selector
[variants]="variants()"
[disabled]="!allows(availability(), 'select_variant')"
[(selectedVariant)]="selectedVariant"
/>
</div>
</div>
}
@@ -42,14 +46,21 @@
<div class="product-vertical-with-cart-card__actions">
<app-button
variant="primary"
[disabled]="unavailable() || (hasVariants() && selectedVariant() === null)"
[disabled]="
!allows(effectiveAvailability(), 'buy_now') ||
(hasVariants() && selectedVariant() === null)
"
(click)="onBuy()"
>
Comprar
</app-button>
<app-button
variant="secondary"
[disabled]="saving() || unavailable() || (hasVariants() && selectedVariant() === null)"
[disabled]="
saving() ||
!allows(effectiveAvailability(), 'add_to_cart') ||
(hasVariants() && selectedVariant() === null)
"
(click)="onAddToCart()"
>
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}

View File

@@ -58,11 +58,17 @@ describe('ProductVerticalWithCartCardComponent', () => {
it('shows the backend availability message with the reusable tooltip', async () => {
const fixture = await createComponent();
fixture.componentRef.setInput('maximumAddableQuantity', 0);
fixture.componentRef.setInput(
'unavailableMessage',
'Alcanzaste el cupo máximo permitido para este producto.',
);
fixture.componentRef.setInput('availability', {
state: 'visible',
maximum_quantity: 0,
reasons: [
{
code: 'user_quota_reached',
message: 'Alcanzaste el cupo máximo permitido para este producto.',
},
],
allowed_actions: [],
});
fixture.detectChanges();
const tooltip = (fixture.nativeElement as HTMLElement).querySelector('app-tooltip');

View File

@@ -15,12 +15,19 @@ import {
VariantSelectorComponent,
VariantSelectorVariant,
} from '../variant-selector/variant-selector.component';
import { CatalogAvailability } from '../../../core/services/catalog/catalog.interface';
import {
AVAILABLE_CATALOG_AVAILABILITY,
allowsCatalogAction,
combineCatalogAvailability,
maximumCatalogQuantity,
primaryAvailabilityMessage,
} from '../../../core/services/catalog/catalog-availability';
export interface VerticalCartVariant extends VariantSelectorVariant {
descripcion?: string | null;
precio?: string | number;
maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
availability?: CatalogAvailability;
}
@Component({
@@ -34,8 +41,7 @@ export class ProductVerticalWithCartCardComponent {
readonly title = input<string>('');
readonly description = input<string>('');
readonly price = input<number>(0);
readonly maximumAddableQuantity = input<number | null>(null);
readonly unavailableMessage = input<string | null>(null);
readonly availability = input<CatalogAvailability>(AVAILABLE_CATALOG_AVAILABILITY);
readonly variants = input<VerticalCartVariant[]>([]);
readonly saving = input(false);
@@ -58,17 +64,16 @@ 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 effectiveAvailability = computed(() =>
combineCatalogAvailability(this.availability(), this.selectedVariantData()?.availability),
);
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
protected readonly effectiveUnavailableMessage = computed(() => {
const selectedVariant = this.selectedVariantData();
return selectedVariant
? (selectedVariant.unavailable_message ?? null)
: this.unavailableMessage();
});
protected readonly effectiveMaximum = computed(() =>
maximumCatalogQuantity(this.effectiveAvailability()),
);
protected readonly effectiveUnavailableMessage = computed(() =>
primaryAvailabilityMessage(this.effectiveAvailability()),
);
protected readonly allows = allowsCatalogAction;
constructor() {
effect(() => {
@@ -81,7 +86,7 @@ export class ProductVerticalWithCartCardComponent {
}
protected onAddToCart(): void {
if (this.saving() || this.unavailable()) {
if (this.saving() || !this.allows(this.effectiveAvailability(), 'add_to_cart')) {
return;
}
@@ -89,7 +94,7 @@ export class ProductVerticalWithCartCardComponent {
}
protected onBuy(): void {
if (this.unavailable()) return;
if (!this.allows(this.effectiveAvailability(), 'buy_now')) return;
this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
}

View File

@@ -62,6 +62,8 @@ describe('VariantSelectorComponent', () => {
]);
fixture.componentRef.setInput('selectedVariant', 2);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
const selects = Array.from(
fixture.nativeElement.querySelectorAll('select'),
@@ -80,6 +82,28 @@ describe('VariantSelectorComponent', () => {
expect(fixture.componentInstance.selectedVariant()).toBe(1);
});
it('does not offer variants whose availability forbids selection', async () => {
await TestBed.configureTestingModule({
imports: [VariantSelectorComponent],
}).compileComponents();
const fixture = TestBed.createComponent(VariantSelectorComponent);
fixture.componentRef.setInput('variants', [
{ id: 1, values: { talle: 'S' } },
{
id: 2,
values: { talle: 'M' },
availability: { state: 'visible', maximum_quantity: 0, allowed_actions: [], reasons: [] },
},
]);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('S');
expect(fixture.nativeElement.textContent).not.toContain('M');
expect(fixture.componentInstance.selectedVariant()).toBe(1);
});
it('requires manual selections when autoSelectFirst is disabled', async () => {
await TestBed.configureTestingModule({
imports: [VariantSelectorComponent],

View File

@@ -10,6 +10,8 @@ import {
untracked,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CatalogAvailability } from '../../../core/services/catalog/catalog.interface';
import { allowsCatalogAction } from '../../../core/services/catalog/catalog-availability';
export interface VariantAttributeOption {
value: string;
@@ -22,6 +24,7 @@ export type VariantAttributeValue = VariantAttributeScalar | VariantAttributeSca
export interface VariantSelectorVariant {
id: unknown;
values: Record<string, VariantAttributeValue>;
availability?: CatalogAvailability;
}
export interface VariantSelectorSelectionChange {
@@ -64,10 +67,12 @@ export class VariantSelectorComponent {
right: VariantAttributeValue | null,
): boolean => left !== null && right !== null && this.sameValue(left, right);
protected readonly attributeKeys = computed(() =>
Array.from(new Set(this.variants().flatMap((variant) => Object.keys(variant.values)))),
Array.from(
new Set(this.getSelectableVariants().flatMap((variant) => Object.keys(variant.values))),
),
);
protected readonly selectors = computed<VariantSelectorGroup[]>(() => {
const variants = this.variants();
const variants = this.getSelectableVariants();
const keys = this.attributeKeys();
const selectedValues = this.selectedValues();
@@ -110,7 +115,7 @@ export class VariantSelectorComponent {
});
effect(() => {
const variants = this.variants();
const variants = this.getSelectableVariants();
const selectedVariant = this.selectedVariant();
const autoSelectFirst = this.autoSelectFirst();
@@ -139,7 +144,7 @@ export class VariantSelectorComponent {
}
protected onValueChange(key: string, value: VariantAttributeValue | null): void {
const variants = this.variants();
const variants = this.getSelectableVariants();
const keys = this.attributeKeys();
const changedIndex = keys.indexOf(key);
const values = { ...this.selectedValues() };
@@ -198,6 +203,14 @@ export class VariantSelectorComponent {
return Array.from(options.values());
}
private getSelectableVariants(): VariantSelectorVariant[] {
return this.variants().filter(
(variant) =>
variant.availability === undefined ||
allowsCatalogAction(variant.availability, 'select_variant'),
);
}
private reconcileManualSelection(
selectedValues: Record<string, VariantAttributeValue>,
variants: VariantSelectorVariant[],