export const useCartStore = defineStore("cart", { state: () => { return { items: [], loading: false, paymentUrl: "", }; }, getters: { count: (state) => state.items.reduce((sum, item) => sum + item.quantity, 0) || 0, find: (state) => (id) => state.items.find((item) => item?.product?.id == id), }, actions: { async get() { const { status, data } = await useFetch("/api/users/current/cart", { headers: { Authorization: useCookie("token") }, }); if (status.value == "success") { this.items = data.value.cart; } }, async clear() { const { status } = await useFetch("/api/users/cart", { headers: { Authorization: useCookie("token") }, method: "delete", body: {}, }); if (status.value == "success") { this.items = []; } }, async create() { if (this.items.length > 0) { const cart = Object.assign([], this.items).map((item) => { item.product = item.product.id; return item; }); this.items = []; const { status } = await useFetch("/api/users/cart", { headers: { Authorization: useCookie("token") }, method: "put", body: { cart }, }); if (status.value == "success") { localStorage.removeItem("cart"); this.get(); } } }, async update(product, quantity = 0) { const token = useCookie("token"); this.loading = true; const cart = { product: product.id }; if (quantity > 0) { //update let item = this.find(product.id); if (item) item.quantity = quantity; if (token.value) { cart.quantity = quantity; const { status, data } = await useFetch("/api/users/cart", { headers: { Authorization: token }, method: "put", body: { cart }, }); if (status.value == "success") { const temp = { product: data.value, quantity }; if (item) item = temp; else this.items.push(temp); } } else { const temp = { product, quantity }; if (item) item = temp; else this.items.push(temp); } } else { //remove if (token.value) { const { status } = await useFetch("/api/users/cart", { headers: { Authorization: useCookie("token") }, method: "patch", body: { cart }, }); if (status.value == "success") { this.items = this.items.filter( (item) => item.product.id != product.id ); } } else { this.items = this.items.filter( (item) => item.product.id != product.id ); } } this.loading = false; }, async createPayment(id) { const { status, data } = await useFetch( `/api/orders/swift/payment/${id}`, { headers: { Authorization: useCookie("token"), method: "post" }, } ); if (status.value == "success") { console.log(data.value.url); this.paymentUrl = data.value.url; window.open(data.value.url, "_blank"); } return { data, status }; }, }, });