102 lines
2.6 KiB
TypeScript
102 lines
2.6 KiB
TypeScript
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
|
|
quantity: number
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
|
|
function updateFavoriteState(product_id: number, value: boolean) {
|
|
const p = productsList.value.find(p => p.product_id === product_id)
|
|
if (p) p.is_favorite = value
|
|
}
|
|
|
|
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',
|
|
body: JSON.stringify({
|
|
id: productId
|
|
}),
|
|
})
|
|
} else {
|
|
await useFetchJson(url, {
|
|
method: 'DELETE',
|
|
})
|
|
}
|
|
|
|
product.is_favorite = !product.is_favorite
|
|
} catch (e: unknown) {
|
|
error.value = e instanceof Error ? e.message : 'Failed to update favorite'
|
|
}
|
|
}
|
|
|
|
return {
|
|
fetchProductList,
|
|
toggleFavorite,
|
|
updateFavoriteState,
|
|
productsList,
|
|
total,
|
|
loading,
|
|
error,
|
|
perPage
|
|
}
|
|
})
|