113 lines
2.9 KiB
JavaScript
113 lines
2.9 KiB
JavaScript
import { defineStore } from "pinia";
|
|
import { api } from "src/boot/axios";
|
|
import { computed, reactive, ref } from "vue";
|
|
|
|
export const useCartStore = defineStore("cart", () => {
|
|
const cart = ref([]);
|
|
const dedicationTxt = ref("");
|
|
const prevProduct = reactive({});
|
|
const currentProduct = reactive({});
|
|
const nextProduct = reactive({});
|
|
const addCartLoadingBtn = ref(false);
|
|
const cartLength = computed(() => cart.value.length);
|
|
const totalPrice = computed(() => {
|
|
return cart.value.reduce((acc, { price }) => {
|
|
if (price) {
|
|
const priceWithoutLetter = price?.replace("€", "");
|
|
return +priceWithoutLetter + acc;
|
|
}
|
|
}, 0);
|
|
});
|
|
|
|
/**
|
|
*
|
|
* @param debug Allow the data console - boolean
|
|
*
|
|
*/
|
|
async function getCart({ debug }) {
|
|
try {
|
|
const { data } = await api.get("cart");
|
|
cart.value = data;
|
|
|
|
if (debug) {
|
|
console.groupCollapsed("%c Cart is fetched!", "color: green;");
|
|
console.table(cart.value);
|
|
console.groupEnd();
|
|
}
|
|
} catch (err) {
|
|
/* throw */ new Error(`FATAL ERROR ::: ${err}`);
|
|
}
|
|
}
|
|
getCart({ debug: true });
|
|
|
|
/**
|
|
*
|
|
* @param id Id to get product
|
|
* @returns 'id: number; title: string; description: string; price: string; sku: string; category: string; images: string[]'
|
|
*
|
|
*/
|
|
async function getProduct(id) {
|
|
if (id) {
|
|
try {
|
|
const { data } = await api.get(`flowers/${id}`);
|
|
currentProduct.value = data;
|
|
const { data: dataNext } = await api.get(`flowers/${id + 1}`);
|
|
if (dataNext) {
|
|
nextProduct.value = dataNext;
|
|
}
|
|
|
|
console.groupCollapsed("%c Produtos recebido!", "color: green;");
|
|
if (id - 1 > 0) {
|
|
const { data: dataPrev } = await api.get(`flowers/${id - 1}`);
|
|
prevProduct.value = dataPrev;
|
|
console.table(prevProduct.value);
|
|
}
|
|
console.table(currentProduct.value);
|
|
console.table(nextProduct.value);
|
|
console.groupEnd();
|
|
} catch (err) {
|
|
new Error(`FATAL ERROR ::: ${err}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
async function addToCart(product, dedication) {
|
|
cart.value.push({ ...product.value });
|
|
dedicationTxt.value = dedication;
|
|
addCartLoadingBtn.value = true;
|
|
|
|
try {
|
|
await api.post("cart", product);
|
|
addCartLoadingBtn.value = false;
|
|
} catch (err) {
|
|
addCartLoadingBtn.value = false;
|
|
new Error(`FATAL ERROR ::: ${err}`);
|
|
}
|
|
|
|
console.groupCollapsed("%c Adicionado com sucesso!", "color: green");
|
|
console.table(cart.value);
|
|
console.groupEnd();
|
|
}
|
|
|
|
function removeFromCart(id) {
|
|
cart.value = cart.value.filter((p) => p.id !== id);
|
|
api.delete(`cart/${id}`);
|
|
}
|
|
|
|
return {
|
|
cart,
|
|
totalPrice,
|
|
dedicationTxt,
|
|
cartLength,
|
|
prevProduct,
|
|
currentProduct,
|
|
nextProduct,
|
|
addCartLoadingBtn,
|
|
|
|
addToCart,
|
|
removeFromCart,
|
|
getProduct,
|
|
getCart,
|
|
};
|
|
});
|