Compare commits

...

3 Commits

9 changed files with 377 additions and 32 deletions

View File

@@ -2,9 +2,15 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { provideRouter, Router } from '@angular/router';
import {
ActivatedRoute,
convertToParamMap,
ParamMap,
provideRouter,
Router,
} from '@angular/router';
import { of } from 'rxjs';
import { BehaviorSubject, of } from 'rxjs';
import { Tenant } from '../../services/tenant.interface';
import { TenantService } from '../../services/tenant.service';
@@ -140,11 +146,13 @@ describe('StoreLayoutComponent', () => {
let cartState = signal<Cart | null>(null);
let authUserState = signal<AuthUser | null>(null);
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
let queryParamMapState: BehaviorSubject<ParamMap>;
beforeEach(async () => {
tenantState = signal<Tenant | null>(tenant);
cartState = signal<Cart | null>(null);
authUserState = signal<AuthUser | null>(null);
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
const isAuthenticatedState = signal(false);
checkoutServiceStub = {
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
@@ -154,6 +162,10 @@ describe('StoreLayoutComponent', () => {
imports: [StoreLayoutComponent],
providers: [
provideRouter([]),
{
provide: ActivatedRoute,
useValue: { queryParamMap: queryParamMapState.asObservable() },
},
{
provide: TenantService,
useValue: {
@@ -213,6 +225,19 @@ describe('StoreLayoutComponent', () => {
expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull();
});
it('opens the cart when requested through the openCart query parameter', () => {
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
queryParamMapState.next(convertToParamMap({ openCart: 'true' }));
fixture.detectChanges();
expect((fixture.componentInstance as any).isCartOpen()).toBe(true);
expect((fixture.nativeElement as HTMLElement).querySelector('app-cart')).not.toBeNull();
});
it('hides the configured header elements when the tenant disables them', () => {
tenantState.set({
...tenant,

View File

@@ -1,5 +1,6 @@
import { Component, computed, inject, OnInit, signal } from '@angular/core';
import { Router, RouterOutlet } from '@angular/router';
import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router, RouterOutlet } from '@angular/router';
import { TenantService } from '../../services/tenant.service';
import { CartService } from '../../services/cart/cart.service';
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
@@ -32,6 +33,8 @@ export class StoreLayoutComponent implements OnInit {
private readonly checkoutService = inject(CheckoutService);
private readonly toastService = inject(ToastService);
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly destroyRef = inject(DestroyRef);
protected readonly isCartOpen = signal(false);
protected readonly isCreatingPurchase = signal(false);
@@ -146,6 +149,12 @@ export class StoreLayoutComponent implements OnInit {
});
ngOnInit(): void {
this.route.queryParamMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
if (params.get('openCart') === 'true') {
this.isCartOpen.set(true);
}
});
this.cartService.loadCart().subscribe({
error: (err) => console.error('Error loading cart', err),
});

View File

@@ -3,6 +3,7 @@ import { firstValueFrom } from 'rxjs';
import { environment } from '../../../environments/environment';
import { BaseApiService } from './base-api.service';
import { CartItemVariant } from './cart/cart.interface';
export interface UpdatePurchaseCustomerPayload {
dni: string;
@@ -73,6 +74,7 @@ export interface PurchaseDetailItemResponse {
line_total: string;
source_catalog_item_id: number | null;
source_variant_id: number | null;
variants?: CartItemVariant[];
item_details: {
nombre: string;
descripcion: string | null;
@@ -95,7 +97,7 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
telefono: string | null;
nombre_apellido: string | null;
email: string | null;
items_source: 'purchase';
items_source: 'purchase' | 'cart';
items: PurchaseDetailItemResponse[];
tickets_count?: number;
has_generated_tickets?: boolean;
@@ -174,7 +176,20 @@ export class CheckoutService extends BaseApiService {
purchaseId: number,
itemId: number,
quantity: number,
cartId: number | null = null,
itemsSource: 'purchase' | 'cart' = 'purchase',
): Promise<PurchaseDetailResponse> {
if (itemsSource === 'cart' && cartId !== null) {
await firstValueFrom(
this.http.patch(
`${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`,
{ cantidad: quantity },
),
);
return this.getPurchase(tenantCode, purchaseId);
}
const response = await firstValueFrom(
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
@@ -190,6 +205,51 @@ export class CheckoutService extends BaseApiService {
return purchase;
}
async updateItemVariant(
tenantCode: string,
purchaseId: number,
itemId: number,
variantId: number,
quantity: number,
cartId: number | null = null,
itemsSource: 'purchase' | 'cart' = 'purchase',
): Promise<PurchaseDetailResponse> {
if (itemsSource === 'cart' && cartId !== null) {
await firstValueFrom(
this.http.patch(
`${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`,
{ cantidad: quantity, variant_id: variantId },
),
);
} else {
await firstValueFrom(
this.http.patch(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
{ quantity, variant_id: variantId },
),
);
}
return this.getPurchase(tenantCode, purchaseId);
}
async removeItem(
tenantCode: string,
purchaseId: number,
itemId: number,
cartId: number | null = null,
itemsSource: 'purchase' | 'cart' = 'purchase',
): Promise<PurchaseDetailResponse> {
const url =
itemsSource === 'cart' && cartId !== null
? `${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`
: `${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`;
await firstValueFrom(this.http.delete(url));
return this.getPurchase(tenantCode, purchaseId);
}
async prepareItemEditing(
tenantCode: string,
purchaseId: number,

View File

@@ -138,6 +138,7 @@ export interface Tenant {
display_seach_bar?: boolean;
display_cart?: boolean;
cart_editing_policy?: CartEditingPolicy;
checkout_editing_policy?: CartEditingPolicy;
display_cart_item_images?: boolean;
social_media?: SocialMedia[];
menues?: Menu[];

View File

@@ -59,18 +59,22 @@
[discount]="cartDiscount()"
[total]="cartTotal()"
[readonly]="!canModifyCart()"
[allowModify]="canModifyCart()"
[allowModify]="true"
[showModifyWhenReadonly]="true"
[allowUpdateQuantity]="canUpdateCartQuantity()"
[requireEditingMode]="
createdPurchase()?.status === 'created' || createdPurchase()?.status === 'pending_payment'
"
[allowDelete]="false"
[allowUpdateVariant]="canUpdateCartVariant()"
[requireEditingMode]="true"
[allowDelete]="canDeleteCartItems()"
[persistQuantityChanges]="false"
[persistVariantChanges]="false"
[persistDeleteChanges]="false"
[editing]="isEditingItems()"
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"
backgroundColor="transparent"
(editingChange)="onEditingItemsChange($event)"
(itemQuantityChange)="onPurchaseItemQuantityChange($event)"
(itemVariantChange)="onPurchaseItemVariantChange($event)"
(itemRemove)="onPurchaseItemRemove($event)"
/>
</div>
</div>

View File

@@ -18,6 +18,8 @@ describe('CheckoutPageComponent payment validation', () => {
startCheckout: ReturnType<typeof vi.fn>;
updateCustomerData: ReturnType<typeof vi.fn>;
updateItemQuantity: ReturnType<typeof vi.fn>;
updateItemVariant: ReturnType<typeof vi.fn>;
removeItem: ReturnType<typeof vi.fn>;
prepareItemEditing: ReturnType<typeof vi.fn>;
cancelPurchase: ReturnType<typeof vi.fn>;
generatePaymentIntent: ReturnType<typeof vi.fn>;
@@ -36,7 +38,7 @@ describe('CheckoutPageComponent payment validation', () => {
let tenantState: ReturnType<
typeof signal<{
codigo: string;
cart_editing_policy?: CartEditingPolicy;
checkout_editing_policy?: CartEditingPolicy;
}>
>;
@@ -60,6 +62,8 @@ describe('CheckoutPageComponent payment validation', () => {
}),
updateCustomerData: vi.fn(),
updateItemQuantity: vi.fn(),
updateItemVariant: vi.fn(),
removeItem: vi.fn(),
prepareItemEditing: vi.fn(),
cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }),
generatePaymentIntent: vi.fn().mockResolvedValue({
@@ -95,7 +99,7 @@ describe('CheckoutPageComponent payment validation', () => {
authUserState = signal(null);
tenantState = signal({
codigo: 'tenant-test',
cart_editing_policy: {
checkout_editing_policy: {
code: 'full',
allow_modify: true,
allow_delete: true,
@@ -209,19 +213,27 @@ describe('CheckoutPageComponent payment validation', () => {
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
});
it('checks the purchase detail once when the transfer was made', async () => {
it('polls a transfer every three seconds up to four attempts', async () => {
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
const { component } = createComponent();
component.selectedPaymentMethod.set('transfer');
await component.onComplete();
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
component.onComplete();
expect(component.transferValidationStatus()).toBe('checking');
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
for (let attempt = 1; attempt <= 3; attempt += 1) {
await vi.advanceTimersByTimeAsync(3_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(attempt);
expect(component.transferValidationStatus()).toBe('checking');
}
await vi.advanceTimersByTimeAsync(3_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
expect(component.transferValidationStatus()).toBe('error');
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(30_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(1);
});
it('navigates after a transfer is confirmed as paid', async () => {
@@ -229,26 +241,46 @@ describe('CheckoutPageComponent payment validation', () => {
const { component } = createComponent();
component.selectedPaymentMethod.set('transfer');
await component.onComplete();
component.onComplete();
await vi.advanceTimersByTimeAsync(3_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
});
it('shows a retryable state when transfer validation fails', async () => {
it('keeps polling after transfer validation requests fail', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined);
checkoutServiceStub.getPurchase.mockRejectedValue(new Error('network error'));
const { component } = createComponent();
component.selectedPaymentMethod.set('transfer');
await component.onComplete();
component.onComplete();
await vi.advanceTimersByTimeAsync(12_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
expect(component.transferValidationStatus()).toBe('error');
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).not.toHaveBeenCalled();
});
it('cancels transfer polling when the payment method changes or the component is destroyed', async () => {
const first = createComponent();
first.component.selectedPaymentMethod.set('transfer');
first.component.onComplete();
checkoutServiceStub.generatePaymentIntent.mockResolvedValueOnce({});
await first.component.selectPaymentMethod('qr');
await vi.advanceTimersByTimeAsync(12_000);
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
const second = createComponent();
second.component.selectedPaymentMethod.set('transfer');
second.component.onComplete();
second.fixture.destroy();
await vi.advanceTimersByTimeAsync(12_000);
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
});
it('loads purchase items but prefills customer data from the user', async () => {
const purchase = {
id: 25,
@@ -448,7 +480,14 @@ describe('CheckoutPageComponent payment validation', () => {
quantity: 3,
});
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith('tenant-test', 25, 91, 3);
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith(
'tenant-test',
25,
91,
3,
null,
'purchase',
);
expect(component.createdPurchase()).toBe(updatedPurchase);
expect(component.isUpdatingItem()).toBe(false);
});
@@ -481,10 +520,10 @@ describe('CheckoutPageComponent payment validation', () => {
expect(component.isEditingItems()).toBe(false);
});
it('does not allow item editing when the tenant disables cart editing', async () => {
it('shows Modificar and returns to the home cart when checkout editing is disabled', async () => {
tenantState.set({
codigo: 'tenant-test',
cart_editing_policy: {
checkout_editing_policy: {
code: 'disabled',
allow_modify: false,
allow_delete: false,
@@ -492,7 +531,37 @@ describe('CheckoutPageComponent payment validation', () => {
allow_update_variant: false,
},
});
const { component } = createComponent();
const { fixture, component } = createComponent();
component.createdPurchase.set({
id: 25,
status: 'created',
items: [
{
id: 91,
quantity: 2,
unit_price: '100.00',
line_total: '200.00',
source_catalog_item_id: 8,
source_variant_id: null,
item_details: {
nombre: 'Remera',
descripcion: null,
slug: 'remera',
imagen: null,
attributes: [],
},
},
],
subtotal: '200.00',
total: '200.00',
});
fixture.detectChanges();
const modifyButton = (fixture.nativeElement as HTMLElement).querySelector('.cart-edit-btn');
expect(modifyButton?.textContent?.trim()).toBe('Modificar');
expect(
(fixture.nativeElement as HTMLElement).querySelector('app-quantity-selector'),
).toBeNull();
await component.onEditingItemsChange(true);
@@ -500,6 +569,9 @@ describe('CheckoutPageComponent payment validation', () => {
expect(component.canModifyCart()).toBe(false);
expect(component.isEditingItems()).toBe(false);
expect(checkoutServiceStub.prepareItemEditing).not.toHaveBeenCalled();
expect(routerStub.navigate).toHaveBeenCalledWith(['/'], {
queryParams: { openCart: true },
});
});
it('updates customer data on the existing purchase before payment', async () => {

View File

@@ -60,10 +60,15 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
private readonly cartService = inject(CartService);
private readonly qrPollingIntervalMs = 5_000;
private readonly qrPollingMaxAttempts = 9;
private readonly transferPollingIntervalMs = 3_000;
private readonly transferPollingMaxAttempts = 4;
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
private qrPollingAttempts = 0;
private qrPollingRunId = 0;
private transferPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
private transferPollingAttempts = 0;
private transferPollingRunId = 0;
private paymentMethodRequestId = 0;
private navigationStarted = false;
@@ -80,10 +85,16 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
protected readonly isLoadingPurchase = signal(true);
protected readonly checkoutStepIndex = signal(0);
protected readonly canUpdateCartQuantity = computed(
() => this.tenantService.tenant()?.cart_editing_policy?.allow_update_quantity ?? false,
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_update_quantity ?? false,
);
protected readonly canUpdateCartVariant = computed(
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_update_variant ?? false,
);
protected readonly canDeleteCartItems = computed(
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_delete ?? false,
);
protected readonly canModifyCart = computed(
() => this.tenantService.tenant()?.cart_editing_policy?.allow_modify ?? false,
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_modify ?? false,
);
protected readonly cartSubtotal = computed(() => {
@@ -161,6 +172,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
ngOnDestroy(): void {
this.stopQrPolling();
this.stopTransferPolling();
}
private mapPurchaseItemToMock(item: PurchaseDetailItemResponse): CartItemMock {
@@ -176,6 +188,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
value: attribute.value === null ? '' : String(attribute.value),
})),
quantity: item.quantity,
variantId: item.source_variant_id,
variants: item.variants,
};
}
@@ -185,6 +199,9 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
}
if (editing && !this.canModifyCart()) {
await this.router.navigate(['/'], {
queryParams: { openCart: true },
});
return;
}
@@ -200,6 +217,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.isEditingItems.set(true);
this.stopQrPolling();
this.stopTransferPolling();
this.qrData.set(null);
this.qrPaymentStatus.set('idle');
this.transferAccount.set(null);
@@ -251,6 +269,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
purchaseId,
itemId,
event.quantity,
this.createdPurchase()?.cart_id ?? null,
this.createdPurchase()?.items_source ?? 'purchase',
);
this.createdPurchase.set(purchase);
} catch (error) {
@@ -260,6 +280,79 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
}
}
protected async onPurchaseItemVariantChange(event: {
item: CartItemMock;
variantId: number;
}): Promise<void> {
const tenant = this.tenantService.tenant();
const purchase = this.createdPurchase();
const itemId = event.item.cartItemId;
if (
!this.canUpdateCartVariant() ||
!tenant ||
!purchase ||
!itemId ||
this.isUpdatingItem() ||
!this.isEditingItems()
) {
return;
}
this.isUpdatingItem.set(true);
try {
this.createdPurchase.set(
await this.checkoutService.updateItemVariant(
tenant.codigo,
purchase.id,
itemId,
event.variantId,
event.item.quantity,
purchase.cart_id,
purchase.items_source,
),
);
} catch (error) {
console.error('Failed to update purchase item variant:', error);
} finally {
this.isUpdatingItem.set(false);
}
}
protected async onPurchaseItemRemove(event: { item: CartItemMock }): Promise<void> {
const tenant = this.tenantService.tenant();
const purchase = this.createdPurchase();
const itemId = event.item.cartItemId;
if (
!this.canDeleteCartItems() ||
!tenant ||
!purchase ||
!itemId ||
this.isUpdatingItem() ||
!this.isEditingItems()
) {
return;
}
this.isUpdatingItem.set(true);
try {
this.createdPurchase.set(
await this.checkoutService.removeItem(
tenant.codigo,
purchase.id,
itemId,
purchase.cart_id,
purchase.items_source,
),
);
} catch (error) {
console.error('Failed to remove purchase item:', error);
} finally {
this.isUpdatingItem.set(false);
}
}
protected async onStep1Continue(): Promise<void> {
if (this.form.invalid || this.isUpdatingPurchase() || this.isEditingItems()) return;
@@ -299,6 +392,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
public async canDeactivate(): Promise<boolean> {
this.stopQrPolling();
this.stopTransferPolling();
if (this.navigationStarted) {
return true;
@@ -335,6 +429,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
}
this.stopQrPolling();
this.stopTransferPolling();
this.qrPaymentStatus.set('idle');
this.transferValidationStatus.set('idle');
this.selectedPaymentMethod.set(method);
@@ -392,6 +487,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
}
this.transferDni.set(dni);
this.stopTransferPolling();
this.transferValidationStatus.set('idle');
this.isGeneratingIntent.set(true);
try {
@@ -432,7 +528,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
}
}
protected async onComplete(): Promise<void> {
protected onComplete(): void {
const purchaseId = this.createdPurchaseId();
const tenant = this.tenantService.tenant();
@@ -446,22 +542,72 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return;
}
this.stopTransferPolling();
this.transferValidationStatus.set('checking');
this.transferPollingAttempts = 0;
const runId = this.transferPollingRunId;
this.scheduleTransferPoll(runId);
}
private scheduleTransferPoll(runId: number): void {
this.transferPollingTimeoutId = setTimeout(() => {
this.transferPollingTimeoutId = null;
void this.checkTransferPayment(runId);
}, this.transferPollingIntervalMs);
}
private async checkTransferPayment(runId: number): Promise<void> {
if (runId !== this.transferPollingRunId) {
return;
}
const purchaseId = this.createdPurchaseId();
const tenant = this.tenantService.tenant();
if (!purchaseId || !tenant || this.selectedPaymentMethod() !== 'transfer') {
this.stopTransferPolling();
return;
}
this.transferPollingAttempts += 1;
try {
const purchase = await this.checkoutService
.withCustomLoading()
.getPurchase(tenant.codigo, purchaseId);
if (runId !== this.transferPollingRunId) {
return;
}
if (purchase.status === 'paid') {
this.navigateToPurchaseStatus(purchaseId);
return;
}
this.transferValidationStatus.set('error');
} catch (error) {
console.error('Failed to validate transfer payment:', error);
}
if (runId !== this.transferPollingRunId) {
return;
}
if (this.transferPollingAttempts >= this.transferPollingMaxAttempts) {
this.stopTransferPolling();
this.transferValidationStatus.set('error');
return;
}
this.scheduleTransferPoll(runId);
}
private stopTransferPolling(): void {
this.transferPollingRunId += 1;
if (this.transferPollingTimeoutId !== null) {
clearTimeout(this.transferPollingTimeoutId);
this.transferPollingTimeoutId = null;
}
}
@@ -575,6 +721,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.navigationStarted = true;
this.stopQrPolling();
this.stopTransferPolling();
void this.router.navigate(['/checkout/status', purchaseId]);
}

View File

@@ -6,7 +6,12 @@
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
<div class="d-flex align-items-center cart-header-actions">
@if (!readonly() && allowModify() && requireEditingMode() && items().length > 0) {
@if (
allowModify() &&
(!readonly() || showModifyWhenReadonly()) &&
requireEditingMode() &&
items().length > 0
) {
<button
class="btn btn-link p-0 border-0 cart-edit-btn"
type="button"

View File

@@ -55,10 +55,13 @@ export class CartComponent {
readonly readonly = input<boolean>(false);
readonly allowUpdateQuantity = input<boolean>(true);
readonly allowModify = input<boolean>(true);
readonly showModifyWhenReadonly = input<boolean>(false);
readonly requireEditingMode = input<boolean>(false);
readonly allowUpdateVariant = input<boolean>(true);
readonly allowDelete = input<boolean>(true);
readonly persistQuantityChanges = input<boolean>(true);
readonly persistVariantChanges = input<boolean>(true);
readonly persistDeleteChanges = input<boolean>(true);
readonly editingDisabled = input<boolean>(false);
readonly editing = model<boolean>(false);
@@ -68,6 +71,12 @@ export class CartComponent {
index: number;
quantity: number;
}>();
readonly itemVariantChange = output<{
item: CartItemMock;
index: number;
variantId: number;
}>();
readonly itemRemove = output<{ item: CartItemMock; index: number }>();
protected readonly quantityOverrides = signal<Record<number, number>>({});
protected readonly variantOverrides = signal<Record<number, number>>({});
@@ -179,6 +188,12 @@ export class CartComponent {
if (!item || !cartItemId || variantId === this.getItemVariant(item)) return;
this.itemVariantChange.emit({ item, index, variantId });
if (!this.persistVariantChanges()) {
return;
}
this.variantOverrides.update((overrides) => ({ ...overrides, [cartItemId]: variantId }));
this.cartService
.updateItemVariant(cartItemId, this.getItemQuantity(item), variantId)
@@ -221,8 +236,15 @@ export class CartComponent {
})
.subscribe((confirmed) => {
if (confirmed) {
const item = this.items()[index];
if (item) {
this.itemRemove.emit({ item, index });
}
if (this.persistDeleteChanges()) {
this.removeItem(target.cartItemId);
}
}
});
}