Files
interview-demo-code/spa/src/stores/CartStore.js
2025-08-05 21:53:39 +03:00

109 lines
3.8 KiB
JavaScript

import {defineStore} from "pinia";
import {isNotEmpty} from "@/helpers.js";
import {addToCart, cartEditItem, cartRemoveItem, getCart} from "@/utils/ftch.js";
export const useCartStore = defineStore('cart', {
state: () => ({
items: [],
productsCount: 0,
total: 0,
isLoading: false,
reason: null,
error_warning: '',
attention: '',
success: '',
}),
getters: {
canCheckout: (state) => {
if (state.isLoading || state.error_warning.length > 0) {
return false;
}
},
},
actions: {
async getProducts() {
try {
this.isLoading = true;
const {data} = await getCart();
this.items = data.products;
this.productsCount = data.total_products_count;
this.totals = data.totals;
this.error_warning = data.error_warning;
this.attention = data.attention;
this.success = data.success;
} catch (error) {
console.error(error);
} finally {
this.isLoading = false;
}
},
async addProduct(productId, productName, price, quantity = 1, options = []) {
try {
this.isLoading = true;
const formData = new FormData();
formData.append("product_id", productId);
formData.append("quantity", quantity);
// TODO: Add support different types of options
options.forEach((option) => {
if (option.type === "checkbox" && Array.isArray(option.value)) {
option.value.forEach(item => {
formData.append(`option[${option.product_option_id}][]`, item.product_option_value_id);
});
} else if (option.type === "radio" && isNotEmpty(option.value)) {
formData.append(`option[${option.product_option_id}]`, option.value.product_option_value_id);
} else if (option.type === "select" && isNotEmpty(option.value)) {
formData.append(`option[${option.product_option_id}]`, option.value.product_option_value_id);
} else if ((option.type === "text" || option.type === 'textarea') && isNotEmpty(option.value)) {
formData.append(`option[${option.product_option_id}]`, option.value);
}
})
const response = await addToCart(formData);
if (response.error) {
throw new Error(JSON.stringify(response.error));
}
await this.getProducts();
} catch (error) {
console.log(error);
throw error;
} finally {
this.isLoading = false;
}
},
async removeItem(rowId) {
try {
this.isLoading = true;
const formData = new FormData();
formData.append('key', rowId);
await cartRemoveItem(formData);
await this.getProducts();
} catch (error) {
console.error(error);
} finally {
this.isLoading = false;
}
},
async setQuantity(cartId, quantity) {
try {
this.isLoading = true;
const formData = new FormData();
formData.append(`quantity[${cartId}]`, quantity);
await cartEditItem(formData);
await this.getProducts();
} catch (error) {
console.log(error);
} finally {
this.isLoading = false;
}
},
},
});