Compare commits

...

13 Commits

Author SHA1 Message Date
72c80465e8 test(catalog): cover global availability behavior 2026-08-25 09:03:32 -03:00
5273459b64 feat(catalog): consume global availability decisions 2026-08-25 09:03:23 -03:00
3ec469a539 test(catalog): update availability contract fixtures 2026-08-24 15:16:13 -03:00
f02f4456b7 feat(catalog): adopt subject-aware availability contract 2026-08-24 15:16:00 -03:00
eda8d32f4e test(catalog): cover availability-driven controls 2026-08-24 14:33:25 -03:00
5ca1f03e20 feat(catalog): consume availability capabilities 2026-08-24 14:33:11 -03:00
8861e42fff fix(stepper): add disabled state to prevent navigation and provide visual feedback 2026-08-24 14:07:12 -03:00
7fbdd3844f fix(purchase-detail): add in-review section with WhatsApp contact option 2026-08-24 12:35:33 -03:00
f2c1542e46 fix(purchase-list): refactor purchase list to consolidate in-review and paid purchases, add status message display 2026-08-24 12:35:25 -03:00
def86405dc fix(purchase-list): conditionally render paginator for in-review and paid purchases 2026-08-24 09:17:27 -03:00
870de3ca6e feat(purchase-list): implement pagination for in-review and paid purchases 2026-08-24 09:16:52 -03:00
d8d489e846 fix(checkout): increase polling max attempts for QR and transfer payments 2026-08-22 23:08:20 +00:00
4183d6386d fix(checkout): increase polling max attempts for QR and transfer payments 2026-08-22 23:06:38 +00:00
40 changed files with 819 additions and 242 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 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 { export interface CatalogVariantOption {
value: string; value: string;
label: string; label: string;
@@ -66,8 +85,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[];
maximum_addable_quantity?: number | null; availability: CatalogAvailability;
unavailable_message?: string | null;
minimum_use_date?: string | null; minimum_use_date?: string | null;
maximum_use_date?: string | null; maximum_use_date?: string | null;
effective_minimum_use_date?: string | null; effective_minimum_use_date?: string | null;
@@ -99,7 +117,7 @@ export interface CatalogItemDetail {
attributes: ProductAttribute[]; attributes: ProductAttribute[];
variants: CatalogItemVariant[]; variants: CatalogItemVariant[];
selected_variant?: SelectedCatalogItemVariant; selected_variant?: SelectedCatalogItemVariant;
maximum_addable_quantity?: number | null; availability: CatalogAvailability;
images?: string[]; images?: string[];
} }
@@ -114,8 +132,7 @@ export interface CatalogFeaturedItemVariant {
id: number; id: number;
descripcion?: string | null; descripcion?: string | null;
precio?: string; precio?: string;
maximum_addable_quantity?: number | null; availability: CatalogAvailability;
unavailable_message?: string | null;
values: Record<string, CatalogVariantValue>; values: Record<string, CatalogVariantValue>;
} }
@@ -147,8 +164,7 @@ export interface CatalogFeaturedItem {
descripcion?: string | null; descripcion?: string | null;
precio: number | string; precio: number | string;
image?: string | null; image?: string | null;
maximum_addable_quantity?: number | null; availability: CatalogAvailability;
unavailable_message?: string | null;
variants?: CatalogFeaturedItemVariant[]; variants?: CatalogFeaturedItemVariant[];
} }

View File

@@ -2,6 +2,8 @@ import { Injectable } from '@angular/core';
import { firstValueFrom } from 'rxjs'; import { firstValueFrom } from 'rxjs';
import { environment } from '../../../environments/environment'; import { environment } from '../../../environments/environment';
import { ApiPaginatedResponse } from './api-paginated-response.interface';
import { ApiPaginationQueryParams } from './api-pagination-query-params.interface';
import { BaseApiService } from './base-api.service'; import { BaseApiService } from './base-api.service';
export interface UpdatePurchaseCustomerPayload { export interface UpdatePurchaseCustomerPayload {
@@ -226,12 +228,20 @@ export class CheckoutService extends BaseApiService {
async getPurchases( async getPurchases(
tenantCode: string, tenantCode: string,
status?: string, status?: string,
): Promise<{ data: PurchaseSummaryResponse[] }> { pagination: ApiPaginationQueryParams = {},
let url = `${environment.url}tenants/${tenantCode}/compras`; ): Promise<ApiPaginatedResponse<PurchaseSummaryResponse[]>> {
if (status) { const params: Record<string, string | number> = {};
url += `?status=${status}`;
} if (status) params['status'] = status;
const response = await firstValueFrom(this.http.get<{ data: PurchaseSummaryResponse[] }>(url)); if (pagination.page) params['page'] = pagination.page;
if (pagination.per_page) params['per_page'] = pagination.per_page;
const response = await firstValueFrom(
this.http.get<ApiPaginatedResponse<PurchaseSummaryResponse[]>>(
`${environment.url}tenants/${tenantCode}/compras`,
{ params },
),
);
if (!response) { if (!response) {
throw new Error('Error al obtener las compras.'); throw new Error('Error al obtener las compras.');
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -6,7 +6,11 @@
} @else { } @else {
<div class="checkout-page"> <div class="checkout-page">
<div class="checkout-page__stepper-col"> <div class="checkout-page__stepper-col">
<app-stepper #stepper [initialStepIndex]="checkoutStepIndex()"> <app-stepper
#stepper
[initialStepIndex]="checkoutStepIndex()"
[disabled]="hasSubmittedTransfer()"
>
<app-step label="Datos" [isValid]="isStep1Valid()"> <app-step label="Datos" [isValid]="isStep1Valid()">
<app-checkout-data-step <app-checkout-data-step
[form]="form" [form]="form"

View File

@@ -69,9 +69,9 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
private readonly toastService = inject(ToastService); private readonly toastService = inject(ToastService);
private readonly cartService = inject(CartService); private readonly cartService = inject(CartService);
private readonly qrPollingIntervalMs = 5_000; private readonly qrPollingIntervalMs = 5_000;
private readonly qrPollingMaxAttempts = 9; private readonly qrPollingMaxAttempts = 120;
private readonly transferPollingIntervalMs = 3_000; private readonly transferPollingIntervalMs = 3_000;
private readonly transferPollingMaxAttempts = 4; private readonly transferPollingMaxAttempts = 209;
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null; private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
private qrPollingAttempts = 0; private qrPollingAttempts = 0;

View File

@@ -44,6 +44,7 @@
[variants]="prod.variants" [variants]="prod.variants"
[selectedVariant]="prod.selected_variant ?? null" [selectedVariant]="prod.selected_variant ?? null"
[inventoryPolicy]="prod.inventory_policy" [inventoryPolicy]="prod.inventory_policy"
[disabled]="!allows(prod.availability, 'select_variant')"
(variantChange)="onVariantChange($event)" (variantChange)="onVariantChange($event)"
/> />
</section> </section>
@@ -53,14 +54,22 @@
<section class="product-detail__section"> <section class="product-detail__section">
<div class="product-detail__purchase"> <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"> <div class="product-detail__actions">
<app-button <app-button
class="product-detail__cta" class="product-detail__cta"
variant="secondary" variant="secondary"
type="button" type="button"
[disabled]="!selectedVariantAvailable() || variantLoading() || addingToCart()" [disabled]="!canAddToCart() || variantLoading() || addingToCart()"
(click)="addToCart()" (click)="addToCart()"
> >
@if (addingToCart()) { @if (addingToCart()) {
@@ -75,9 +84,7 @@
<app-button <app-button
class="product-detail__cta" class="product-detail__cta"
type="button" type="button"
[disabled]=" [disabled]="!canBuyNow() || variantLoading() || creatingDirectPurchase()"
!selectedVariantAvailable() || variantLoading() || creatingDirectPurchase()
"
(click)="buyNow()" (click)="buyNow()"
> >
@if (variantLoading() || creatingDirectPurchase()) { @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 { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../../core/services/catalog/catalog.service'; import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service'; import { 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 { CartService } from '../../../../core/services/cart/cart.service';
import { ToastService } from '../../../../core/services/toast.service'; import { ToastService } from '../../../../core/services/toast.service';
import { ProductDetailPageComponent } from './product-detail-page.component'; import { ProductDetailPageComponent } from './product-detail-page.component';
@@ -38,7 +39,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,
maximum_addable_quantity: 10, availability: createCatalogAvailability(10),
attributes: [], attributes: [],
variants: [], variants: [],
}; };
@@ -179,7 +180,7 @@ describe('ProductDetailPageComponent', () => {
it('reloads product availability when the cart changes', async () => { it('reloads product availability when the cart changes', async () => {
catalogServiceStub.getCatalogItem.mockReturnValue( catalogServiceStub.getCatalogItem.mockReturnValue(
of({ ...mockProduct, maximum_addable_quantity: 4 }), of({ ...mockProduct, availability: createCatalogAvailability(4) }),
); );
await configureTestingModule(); await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent); const fixture = TestBed.createComponent(ProductDetailPageComponent);
@@ -192,6 +193,21 @@ describe('ProductDetailPageComponent', () => {
expect(fixture.componentInstance['selectedVariantMax']()).toBe(4); 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 () => { it('shows error message if the resolver cannot load the product', async () => {
resolveProductError(PRODUCT_DETAIL_ERROR_MESSAGE); resolveProductError(PRODUCT_DETAIL_ERROR_MESSAGE);
await configureTestingModule(); await configureTestingModule();
@@ -207,10 +223,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, maximum_addable_quantity: 10, values: {} }], variants: [{ id: 123, availability: createCatalogAvailability(10), values: {} }],
selected_variant: { selected_variant: {
id: 123, id: 123,
maximum_addable_quantity: 10, availability: createCatalogAvailability(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: {},
}, },
@@ -312,11 +328,15 @@ describe('ProductDetailPageComponent', () => {
}, },
], ],
variants: [ variants: [
{ id: 123, maximum_addable_quantity: 10, values: { color: 'beige', material: 'Cuero' } }, {
id: 123,
availability: createCatalogAvailability(10),
values: { color: 'beige', material: 'Cuero' },
},
], ],
selected_variant: { selected_variant: {
id: 123, id: 123,
maximum_addable_quantity: 10, availability: createCatalogAvailability(10),
images: ['https://example.com/variant1.png'], images: ['https://example.com/variant1.png'],
values: { values: {
color: 'beige', color: 'beige',
@@ -353,8 +373,18 @@ describe('ProductDetailPageComponent', () => {
purpose: 'entry', purpose: 'entry',
has_tickets: true, has_tickets: true,
variants: [ 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: [ attributes: [
{ {
@@ -385,7 +415,7 @@ describe('ProductDetailPageComponent', () => {
selected_variant: { selected_variant: {
id: 101, id: 101,
event_date_id: 20, event_date_id: 20,
maximum_addable_quantity: 10, availability: createCatalogAvailability(10),
images: [], images: [],
values: {}, values: {},
}, },
@@ -407,6 +437,8 @@ describe('ProductDetailPageComponent', () => {
options[1].click(); options[1].click();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, 102); expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, 102);
}); });
@@ -429,7 +461,7 @@ describe('ProductDetailPageComponent', () => {
fixture.componentInstance['selectedVariant'].set({ fixture.componentInstance['selectedVariant'].set({
id: 1, id: 1,
maximum_addable_quantity: 10, availability: createCatalogAvailability(10),
values: {}, values: {},
}); });
fixture.detectChanges(); fixture.detectChanges();
@@ -519,7 +551,7 @@ describe('ProductDetailPageComponent', () => {
error: { error: {
code: 'purchase.limit_exceeded', code: 'purchase.limit_exceeded',
message: 'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.', 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: [ variants: [
{ {
id: 123, id: 123,
maximum_addable_quantity: 5, availability: createCatalogAvailability(5),
values: {}, values: {},
}, },
], ],
selected_variant: { selected_variant: {
id: 123, id: 123,
maximum_addable_quantity: 5, availability: createCatalogAvailability(5),
images: [], images: [],
values: {}, values: {},
}, },
@@ -583,7 +615,7 @@ describe('ProductDetailPageComponent', () => {
resolveProduct({ resolveProduct({
...mockProduct, ...mockProduct,
variants: [], variants: [],
maximum_addable_quantity: 4, availability: createCatalogAvailability(4),
}); });
await configureTestingModule(); await configureTestingModule();
@@ -609,13 +641,13 @@ describe('ProductDetailPageComponent', () => {
variants: [ variants: [
{ {
id: 123, id: 123,
maximum_addable_quantity: 5, availability: createCatalogAvailability(5),
values: {}, values: {},
}, },
], ],
selected_variant: { selected_variant: {
id: 123, id: 123,
maximum_addable_quantity: 5, availability: createCatalogAvailability(5),
images: [], images: [],
values: {}, values: {},
}, },
@@ -647,7 +679,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,
maximum_addable_quantity: null, availability: createCatalogAvailability(null),
values: {}, values: {},
}; };
resolveProduct({ resolveProduct({
@@ -655,7 +687,7 @@ describe('ProductDetailPageComponent', () => {
inventory_policy: 'unlimited', inventory_policy: 'unlimited',
selected_variant: { selected_variant: {
id: 321, id: 321,
maximum_addable_quantity: null, availability: createCatalogAvailability(null),
images: [], images: [],
values: {}, values: {},
}, },
@@ -679,7 +711,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,
maximum_addable_quantity: 2, availability: createCatalogAvailability(2),
values: {}, values: {},
}; };
resolveProduct({ resolveProduct({
@@ -688,7 +720,7 @@ describe('ProductDetailPageComponent', () => {
max_units_per_user: 2, max_units_per_user: 2,
selected_variant: { selected_variant: {
id: 322, id: 322,
maximum_addable_quantity: 2, availability: createCatalogAvailability(2),
images: [], images: [],
values: { event_date: '20' }, values: { event_date: '20' },
}, },
@@ -712,14 +744,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,
maximum_addable_quantity: 0, availability: createCatalogAvailability(0),
values: {}, values: {},
}; };
resolveProduct({ resolveProduct({
...mockProduct, ...mockProduct,
selected_variant: { selected_variant: {
id: 654, id: 654,
maximum_addable_quantity: 0, availability: createCatalogAvailability(0),
images: [], images: [],
values: {}, values: {},
}, },

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -62,6 +62,8 @@ describe('VariantSelectorComponent', () => {
]); ]);
fixture.componentRef.setInput('selectedVariant', 2); fixture.componentRef.setInput('selectedVariant', 2);
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
const selects = Array.from( const selects = Array.from(
fixture.nativeElement.querySelectorAll('select'), fixture.nativeElement.querySelectorAll('select'),
@@ -80,6 +82,28 @@ describe('VariantSelectorComponent', () => {
expect(fixture.componentInstance.selectedVariant()).toBe(1); 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 () => { it('requires manual selections when autoSelectFirst is disabled', async () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [VariantSelectorComponent], imports: [VariantSelectorComponent],

View File

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