Files
b2b/bo/src/stores/customer/cart.ts
2026-04-15 12:42:20 +02:00

107 lines
2.4 KiB
TypeScript

import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useFetchJson } from '@/composable/useFetchJson'
import type { ApiResponse } from '@/types'
import { useRoute } from 'vue-router'
export interface Cart {
id: number
name: string
items: any[]
}
export const useCartStore = defineStore('cart', () => {
const carts = ref<Cart[]>([])
const activeCartId = ref<number | null>(null)
const error = ref<string | null>(null)
async function fetchCarts() {
try {
const res = await useFetchJson<ApiResponse>(
`/api/v1/restricted/carts/retrieve-carts-info`
)
carts.value = res.items
} catch (e: any) {
error.value = e?.message ?? 'Error loading carts'
}
}
async function addNewCart(name: string) {
try {
error.value = null
const url = `/api/v1/restricted/carts/add-new-cart`
const response = await useFetchJson<ApiResponse>(url)
const newCart: Cart = {
id: response.items.cart_id,
name: response.items.name,
items: []
}
carts.value.push(newCart)
activeCartId.value = newCart.id
return newCart
} catch (e: any) {
error.value = e?.message ?? 'Error creating cart'
}
}
const route = useRoute()
const amount = ref<number>(1);
const errorMessage = ref('');
async function addProduct(product_id: number, count: number) {
if (!activeCartId.value) {
errorMessage.value = 'No active cart selected'
return
}
try {
const res = await useFetchJson<ApiResponse>(
`/api/v1/restricted/carts/add-product-to-cart?cart_id=${activeCartId.value}&product_id=${product_id}&amount=${count}`
)
console.log('fsdfsdfdsfdsfs', res)
} catch (e: any) {
errorMessage.value = e?.message ?? 'Error adding product'
}
}
function setActiveCart(id: number | null) {
activeCartId.value = id
if (id) {
localStorage.setItem('activeCartId', String(id))
} else {
localStorage.removeItem('activeCartId')
}
}
function initCart() {
const saved = localStorage.getItem('activeCartId')
if (saved) {
activeCartId.value = Number(saved)
}
}
const activeCart = computed(() => {
return carts.value.find(c => c.cart_id === activeCartId.value)
})
return {
carts,
activeCartId,
error,
errorMessage,
activeCart,
setActiveCart,
addProduct,
fetchCarts,
addNewCart,
initCart,
}
})