This commit is contained in:
sdarbinyan
2026-06-20 15:16:25 +04:00
parent 51445a7341
commit 6410321895
6 changed files with 98 additions and 13 deletions

View File

@@ -28,6 +28,17 @@ export class CartService {
return total + (getDiscountedPrice(item) * item.quantity);
}, 0);
});
totalDeliveryPrice = computed(() => {
const items = this.cartItems();
if (!Array.isArray(items)) return 0;
return items.reduce((total, item) => total + ((item.deliveryPrice ?? 0) * item.quantity), 0);
});
totalWithDelivery = computed(() => this.totalPrice() + this.totalDeliveryPrice());
hasDeliveryPrice = computed(() => {
const items = this.cartItems();
if (!Array.isArray(items)) return false;
return items.some(item => item.deliveryPrice !== undefined && item.deliveryPrice !== null);
});
constructor(private apiService: ApiService) {
this.loadCart();
@@ -41,6 +52,29 @@ export class CartService {
});
}
private normalizeOptionalNumber(value: unknown): number | undefined {
if (value === null || value === undefined || value === '') {
return undefined;
}
const normalized = typeof value === 'number'
? value
: Number(String(value).replace(',', '.'));
return Number.isFinite(normalized) ? normalized : undefined;
}
private normalizeCartItem(item: CartItem): CartItem {
const { deliveryPrice, ...rest } = item;
const normalizedDeliveryPrice = this.normalizeOptionalNumber(deliveryPrice);
return {
...rest,
quantity: item.quantity || 1,
...(normalizedDeliveryPrice !== undefined ? { deliveryPrice: normalizedDeliveryPrice } : {}),
};
}
private saveToStorage(items: CartItem[]): void {
const data = JSON.stringify(items);
@@ -90,10 +124,7 @@ export class CartService {
try {
const items = JSON.parse(json);
if (Array.isArray(items)) {
this.cartItems.set(items.map(item => ({
...item,
quantity: item.quantity || 1
})));
this.cartItems.set(items.map(item => this.normalizeCartItem(item)));
return true;
}
} catch (err) {
@@ -118,14 +149,14 @@ export class CartService {
this.addingItems.add(itemID);
this.apiService.getItem(itemID).subscribe({
next: (item) => {
const cartItem: CartItem = {
const cartItem = this.normalizeCartItem({
...item,
quantity,
...(variant?.colour != null && { colour: variant.colour }),
...(variant?.size != null && { size: variant.size }),
...(variant?.price != null && { price: variant.price }),
...(variant?.currency != null && { currency: variant.currency }),
};
});
this.cartItems.set([...this.cartItems(), cartItem]);
this.addingItems.delete(itemID);
},