Files
web-frontend/app/composables/useClientCart.ts

122 lines
2.8 KiB
TypeScript

export type ClientCartItem = {
productId: string;
productName: string;
sku: string;
isCustomizable: boolean;
quantity: number;
parameters: {
width: number;
thickness: number;
color: string;
};
};
function normalizeQuantity(value: number) {
if (!Number.isFinite(value) || value < 0) {
return 0;
}
return Math.floor(value);
}
export function useClientCart() {
const items = useState<ClientCartItem[]>('client-cart-items', () => []);
const totalPositions = computed(() => items.value.length);
const totalItems = computed(() => items.value.reduce((sum, item) => sum + item.quantity, 0));
const totalVolume = computed(() =>
items.value.reduce((sum, item) => sum + item.quantity * item.parameters.width * item.parameters.thickness, 0),
);
function getQuantity(productId: string) {
return items.value.find((item) => item.productId === productId)?.quantity ?? 0;
}
function addProduct(product: {
id: string;
name: string;
sku: string;
isCustomizable: boolean;
}) {
const existing = items.value.find((item) => item.productId === product.id);
if (existing) {
existing.quantity += 1;
return;
}
items.value.push({
productId: product.id,
productName: product.name,
sku: product.sku,
isCustomizable: product.isCustomizable,
quantity: 1,
parameters: {
width: 100,
thickness: 50,
color: 'прозрачный',
},
});
}
function setQuantity(productId: string, quantity: number) {
const existing = items.value.find((item) => item.productId === productId);
if (!existing) {
return;
}
const normalizedQuantity = normalizeQuantity(quantity);
if (normalizedQuantity === 0) {
removeProduct(productId);
return;
}
existing.quantity = normalizedQuantity;
}
function incrementQuantity(productId: string) {
const existing = items.value.find((item) => item.productId === productId);
if (!existing) {
return;
}
existing.quantity += 1;
}
function decrementQuantity(productId: string) {
const existing = items.value.find((item) => item.productId === productId);
if (!existing) {
return;
}
const normalizedQuantity = normalizeQuantity(existing.quantity - 1);
if (normalizedQuantity === 0) {
removeProduct(productId);
return;
}
existing.quantity = normalizedQuantity;
}
function removeProduct(productId: string) {
items.value = items.value.filter((item) => item.productId !== productId);
}
function clearCart() {
items.value = [];
}
return {
items,
totalPositions,
totalItems,
totalVolume,
addProduct,
setQuantity,
incrementQuantity,
decrementQuantity,
removeProduct,
clearCart,
getQuantity,
};
}