fix: store customer-product

This commit is contained in:
2026-04-14 08:55:53 +02:00
parent f1a2f4c0b2
commit b54645830f
11 changed files with 276 additions and 141 deletions

View File

@@ -0,0 +1,86 @@
import { useFetchJson } from '@/composable/useFetchJson'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
export interface Product {
id: number
image: string
name: string
productDetails?: string
product_id: number
is_favorite?: boolean
}
export interface ProductResponse {
items: Product[]
items_count: number
}
export interface ApiResponse {
message: string
items: Product[]
count: number
}
export const useCustomerProductStore = defineStore('customer-product', () => {
const loading = ref(true)
const error = ref<string | null>(null)
const route = useRoute()
const productsList = ref<Product[]>([])
const total = ref(0)
const perPage = ref(15)
async function fetchProductList() {
loading.value = true
error.value = null
const params = new URLSearchParams()
Object.entries(route.query).forEach(([key, value]) => {
if (value) params.append(key, String(value))
})
const url = `/api/v1/restricted/product/list?${params}`
try {
const response = await useFetchJson<ApiResponse>(url)
productsList.value = response.items || []
total.value = response.count || 0
} catch (e: unknown) {
error.value = e instanceof Error ? e.message : 'Failed to load products'
} finally {
loading.value = false
}
}
async function toggleFavorite(product: Product) {
const productId = product.product_id
const isFavorite = product.is_favorite
const url = `/api/v1/restricted/product/favorite/${productId}`
try {
if (!isFavorite) {
await useFetchJson(url, { method: 'POST' })
} else {
await useFetchJson(url, { method: 'DELETE' })
}
product.is_favorite = !isFavorite
} catch (e: unknown) {
error.value = e instanceof Error ? e.message : 'Failed to update favorite'
}
}
return {
fetchProductList,
toggleFavorite,
productsList,
total,
loading,
error,
perPage
}
})