fix: cart and products

This commit is contained in:
2026-04-16 12:58:49 +02:00
parent 9b525f06cd
commit fdd3644ec5
11 changed files with 659 additions and 303 deletions

1
bo/components.d.ts vendored
View File

@@ -73,6 +73,7 @@ declare module 'vue' {
UTable: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Table.vue')['default']
UTabs: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Tabs.vue')['default']
UTextarea: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Textarea.vue')['default']
UTooltip: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Tooltip.vue')['default']
UTree: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Tree.vue')['default']
}
}

View File

@@ -1,12 +1,13 @@
<template>
<div class="flex flex-col md:flex-row gap-10">
<div class="w-full flex flex-col items-center gap-4">
<UTable :data="usersList" :columns="columns" class="flex-1 w-full"
:ui="{ root: 'max-w-100wv overflow-auto!' }" />
<UPagination v-model:page="page" :total="total" :items-per-page="perPage" />
</div>
<div class="flex flex-col md:flex-row gap-10">
<div class="w-full flex flex-col items-center gap-4">
<UTable :data="usersList" :columns="columns" class="flex-1 w-full" :ui="{
root: 'max-w-100wv overflow-auto!'
}" />
<UPagination v-model:page="page" :total="total" :items-per-page="perPage" />
</div>
</template>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, resolveComponent, h } from 'vue'

View File

@@ -1,23 +1,25 @@
<template>
<div class="pt-70! flex flex-col items-center justify-center bg-gray-50 dark:bg-(--main-dark)">
<h1 class="text-6xl font-bold text-black dark:text-white mb-14">Search Users</h1>
<div class="pt-70! flex flex-col items-center justify-center bg-gray-50 dark:bg-(--main-dark)">
<h1 class="text-6xl font-bold text-black dark:text-white mb-14">Search Users</h1>
<div class="w-full max-w-4xl">
<UInput icon="i-lucide-search" type="text" placeholder="Type user name or ID..." v-model="searchQuery"
class="w-full!" :ui="{ base: 'py-4! rounded-full!' }" />
</div>
<p v-if="loading">Loading...</p>
<p v-else-if="error" class="text-red-600">{{ error }}</p>
<div v-else-if="clients.length" class="w-full max-w-4xl mt-7">
<UTable :columns="columns" :data="clients" :ui="{ root: 'w-full!' }" />
</div>
<p v-else-if="searchQuery.length" class="pt-4 text-gray-700">
No users found with that name or ID
</p>
<div class="w-full flex flex-col items-center gap-4">
<UInput icon="i-lucide-search" type="text" placeholder="Type user name or ID..." v-model="searchQuery"
class="flex-1 w-full" :ui="{
root: 'max-w-100wv overflow-auto!'
}" />
</div>
</template>
<p v-if="loading">Loading...</p>
<p v-else-if="error" class="text-red-600">{{ error }}</p>
<div v-else-if="clients.length" class="w-full max-w-4xl mt-7">
<UTable :columns="columns" :data="clients" :ui="{ root: 'w-full!' }" />
</div>
<p v-else-if="searchQuery.length" class="pt-4 text-gray-700">
No users found with that name or ID
</p>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, resolveComponent, h } from 'vue'

View File

@@ -1,10 +1,15 @@
<template>
<div class="flex flex-col gap-5 md:gap-10">
<div class="flex flex-col md:flex-row justify-between items-center gap-4">
<h1 class="text-2xl font-bold text-black dark:text-white">{{ t('Shopping Carts') }}</h1>
<div class="flex gap-3">
<UButton color="primary" @click="showCreateModal = true" :disabled="cartStore.carts?.length >= 10"
class="bg-(--accent-blue-light) dark:bg-(--accent-blue-dark) text-white hover:bg-(--accent-blue-dark) dark:hover:bg-(--accent-blue-light)">
<div class="flex items-start gap-2">
<h1 class="text-2xl font-bold text-black dark:text-white">{{ t('Shopping Carts') }}</h1>
<UTooltip :delay-duration="0" text="You can create up to 10 carts.">
<UIcon name="icon-park-outline:attention" class="text-[15px] text-blue-500" />
</UTooltip>
</div>
<div class="flex items-start gap-1">
<UButton color="info" @click="showCreateModal = true" :disabled="cartStore.carts?.length >= 10"
class="">
<UIcon name="mdi:plus" class="mr-1" />
{{ t('New Cart') }}
</UButton>
@@ -44,24 +49,22 @@
</div>
<UModal v-model:open="showCreateModal">
<template #header>
<h3 class="text-lg font-semibold text-black dark:text-white">{{ t('Create New Cart') }}</h3>
</template>
<template #body>
<div class="flex flex-col gap-4">
<UInput v-model="newCartName" :placeholder="t('Cart name')"
class="w-full bg-white dark:bg-gray-800 text-black dark:text-white" />
</div>
</template>
<template #footer>
<div class="flex justify-end gap-2">
<UButton variant="outline" color="neutral" @click="showCreateModal = false">
{{ t('Cancel') }}
</UButton>
<UButton color="primary" @click="createCart" :disabled="!newCartName.trim()"
class="bg-(--accent-blue-light) dark:bg-(--accent-blue-dark) text-white">
{{ t('Create') }}
</UButton>
<div class="flex flex-col gap-5">
<h3 class="text-xl font-bold text-black dark:text-white text-center">{{ t('Create New Cart') }}</h3>
<div class="flex flex-col gap-4">
<UInput v-model="newCartName" :placeholder="t('Cart name')"
class="w-full bg-white dark:bg-gray-800 text-black dark:text-white" />
</div>
<div class="flex justify-end gap-2">
<UButton variant="outline" color="neutral" @click="showCreateModal = false">
{{ t('Cancel') }}
</UButton>
<UButton color="info" @click="createCart" :disabled="!newCartName.trim()"
class="bg-(--accent-blue-light) dark:bg-(--accent-blue-dark) text-white">
{{ t('Create') }}
</UButton>
</div>
</div>
</template>
</UModal>

View File

@@ -1,136 +1,60 @@
<template>
<suspense>
<div class="">
<!-- <UNavigationMenu orientation="vertical" :items="listing" class="data-[orientation=vertical]:w-48">
<template #item="{ item, active }">
<div class="flex items-center gap-2 px-3 py-2">
<UIcon name="i-heroicons-book-open" />
<span>{{ item.name }}</span>
</div>
</template>
</UNavigationMenu> -->
<h1 class="text-2xl font-bold mb-6 text-gray-900 dark:text-white">Products</h1>
<div v-if="customerProductStore.loading" class="text-center py-8">
<span class="text-gray-600 dark:text-gray-400">Loading products...</span>
<div class="">
<h1 class="text-2xl font-bold mb-6 text-gray-900 dark:text-white">Products</h1>
<!-- <div v-if="customerProductStore.loading" class="text-center py-8">
<span class="text-gray-600 dark:text-gray-400">Loading products...</span>
</div> -->
<div v-if="customerProductStore.error" class="mb-4 p-3 bg-red-100 text-red-700 rounded">
{{ customerProductStore.error }}
</div>
<div v-else class="overflow-x-auto">
<div class="flex gap-2">
<CategoryMenu />
<UTable :data="customerProductStore.productsList" :columns="columns" class="flex-1">
<template #expanded="{ row }">
<UTable :data="customerProductStore.productsList.slice(0, 3)" :columns="columnsChild" :ui="{
thead: 'hidden'
}" />
</template>
</UTable>
</div>
<div v-else-if="customerProductStore.error" class="mb-4 p-3 bg-red-100 text-red-700 rounded">
{{ customerProductStore.error }}
<div class="flex justify-center items-center py-8">
<UPagination v-model:page="page" :total="customerProductStore.total"
:page-size="customerProductStore.perPage" />
</div>
<div v-else class="overflow-x-auto">
<div class="flex gap-2">
<CategoryMenu />
<UTable :data="customerProductStore.productsList" :columns="columns" class="flex-1">
<template #expanded="{ row }">
<UTable :data="customerProductStore.productsList.slice(0, 3)" :columns="columnsChild"
:ui="{
thead: 'hidden'
}" />
</template>
</UTable>
</div>
<div class="flex justify-center items-center py-8">
<UPagination v-model:page="page" :total="customerProductStore.total"
:page-size="customerProductStore.perPage" />
</div>
<div v-if="customerProductStore.productsList.length === 0"
class="text-center py-8 text-gray-500 dark:text-gray-400">
No products found
</div>
<div v-if="customerProductStore.productsList.length === 0"
class="text-center py-8 text-gray-500 dark:text-gray-400">
No products found
</div>
</div>
</suspense>
</div>
</suspense>
</template>
<script setup lang="ts">
import { ref, watch, h, resolveComponent, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ref, watch, h, resolveComponent } from 'vue'
import { useRouter } from 'vue-router'
import type { TableColumn } from '@nuxt/ui'
import CategoryMenu from '../inner/CategoryMenu.vue'
import { useCustomerProductStore } from '@/stores/customer/customer-product'
import type { Product } from '@/stores/customer/customer-product'
import { useCartStore } from '@/stores/customer/cart'
import { useToast } from '@nuxt/ui/runtime/composables/useToast.js'
import { useTableState } from '@/composable/useTableState'
import { debounce } from '@/composable/useDebouncedSearch'
const customerProductStore = useCustomerProductStore()
const router = useRouter()
const route = useRoute()
const { page, sortField, filters } = useTableState()
const page = computed({
get: () => Number(route.query.page) || 1,
set: (val: number) => {
router.push({
query: {
...route.query,
page: val
}
})
}
})
const sortField = computed({
get: () => [
route.query.sort as string | undefined,
route.query.direction as 'asc' | 'desc' | undefined
],
set: ([sort]: [string, 'asc' | 'desc']) => {
const currentSort = route.query.sort as string | undefined
const currentDirection = route.query.direction as 'asc' | 'desc' | undefined
let query = { ...route.query }
if (currentSort === sort) {
if (currentDirection === 'asc') {
query.direction = 'desc'
} else if (currentDirection === 'desc') {
delete query.sort
delete query.direction
} else {
query.direction = 'asc'
query.sort = sort
}
} else {
query.sort = sort
query.direction = 'asc'
}
router.push({ query })
}
})
const filters = computed<Record<string, string>>({
get: () => {
const q = { ...route.query }
delete q.page
delete q.sort
delete q.direction
return q as Record<string, string>
},
set: (val) => {
const baseQuery = { ...route.query }
Object.keys(baseQuery).forEach(key => {
if (!['page', 'sort', 'direction'].includes(key)) {
delete baseQuery[key]
}
})
router.push({
query: {
...baseQuery,
...val,
page: 1
}
})
}
})
function debounce(fn: Function, delay = 400) {
let t: any
return (...args: any[]) => {
clearTimeout(t)
t = setTimeout(() => fn(...args), delay)
function getIcon(name: string) {
if (sortField.value[0] === name) {
if (sortField.value[1] === 'asc') return 'i-lucide-arrow-up-narrow-wide'
if (sortField.value[1] === 'desc') return 'i-lucide-arrow-down-wide-narrow'
}
return 'i-lucide-arrow-up-down'
}
const updateFilter = debounce((columnId: string, val: string) => {
@@ -142,29 +66,11 @@ const updateFilter = debounce((columnId: string, val: string) => {
filters.value = newFilters
}, 400)
function goToProduct(productId: number) {
router.push({
name: 'customer-product-details',
params: { product_id: productId }
})
}
const selectedCount = ref({
product_id: null,
product_id: null as number | null,
count: 0
})
function getIcon(name: string) {
if (sortField.value[0] === name) {
if (sortField.value[1] === 'asc') return 'i-lucide-arrow-up-narrow-wide'
if (sortField.value[1] === 'desc') return 'i-lucide-arrow-down-wide-narrow'
}
return 'i-lucide-arrow-up-down'
}
const UInputNumber = resolveComponent('UInputNumber')
const UInput = resolveComponent('UInput')
const UButton = resolveComponent('UButton')
@@ -215,7 +121,6 @@ const columns: TableColumn<Product>[] = [
})
])
},
// header: '#',
cell: ({ row }) => `#${row.getValue('product_id') as number}`
},
{
@@ -442,6 +347,15 @@ const columnsChild: TableColumn<Product>[] = [
}
]
const router = useRouter()
function goToProduct(productId: number) {
router.push({
name: 'customer-product-details',
params: { product_id: productId }
})
}
const cartStore = useCartStore()
const toast = useToast()
async function addToCart(product_id: number) {
@@ -465,11 +379,17 @@ async function addToCart(product_id: number) {
duration: 5000
})
}
watch(
() => route.query,
[filters, sortField, page],
() => {
customerProductStore.fetchProductList()
customerProductStore.fetchProductList({
...filters.value,
sort: sortField.value[0],
direction: sortField.value[1],
page: page.value
})
},
{ immediate: true }
{ immediate: true, deep: true }
)
</script>

View File

@@ -1,154 +1,364 @@
<template>
<div class="pt-70! flex flex-col items-center justify-center bg-gray-50 dark:bg-(--main-dark)">
<h1 class="text-6xl font-bold text-black dark:text-white mb-14">
Search Products
</h1>
<template>
<div class="pt-70! flex flex-col items-center justify-center bg-gray-50 dark:bg-(--main-dark)">
<h1 class="text-6xl font-bold text-black dark:text-white mb-14">
Search Products
</h1>
<div class="w-full max-w-4xl">
<UInput icon="i-lucide-search" type="text" placeholder="Type product name or ID..."
v-model="searchQuery" class="w-full!" :ui="{ base: 'py-4! rounded-full!' }" />
<div class="w-full max-w-4xl flex flex-col gap-2">
<div class="flex items-center gap-2 mt-3 text-gray-600 dark:text-gray-300">
<UCheckbox v-model="searchByReference" />
<span>Search by reference (ID)</span>
</div>
<div v-if="loading" class="mt-6">
Loading...
</div>
<div v-else-if="products.length" class="mt-6 w-full">
<UTable :data="products" :columns="columns" class="flex-1 w-full"
:ui="{ root: 'max-w-100wv overflow-auto!' }" />
</div>
<p v-else-if="searchQuery" class="mt-6">
No products found
</p>
<UInput icon="i-lucide-search" type="text" placeholder="Type product name or ID..."
v-model="searchQuery" class="w-full!" :ui="{ base: 'py-4! rounded-full!' }" />
</div>
</template>
<div v-if="loading" class="mt-6">
Loading...
</div>
<p v-else-if="error" class="mt-6 text-red-500">
{{ error }}
</p>
<div v-else-if="products.length" class="flex items-center w-full">
<UTable :data="products" :columns="columns" class="mt-7" :ui="{ root: 'w-full!' }" />
</div>
<p v-else-if="searchQuery" class="mt-6">
No products found
</p>
</div>
</template>
<script setup lang="ts">
import { useFetchJson } from '@/composable/useFetchJson'
import { ref, watch, computed, resolveComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { debounce } from 'chart.js/helpers'
import { h } from 'vue'
import { ref, watch } from 'vue'
import { h, resolveComponent } from 'vue'
import type { TableColumn } from '@nuxt/ui'
import type { Product } from '@/types/product'
import errorImg from '@/assets/error.svg'
import { useProductSearchApi } from '@/composable/useProductSearchApi'
import { useTableState } from '@/composable/useTableState'
import { debounce } from '@/composable/useDebouncedSearch'
const searchQuery = ref('')
const products = ref<Product[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const {
searchQuery,
products,
loading,
error,
searchByReference,
selectedCount,
fetchProducts,
addToCart,
goToProduct
} = useProductSearchApi()
async function fetchProducts() {
if (!searchQuery.value.trim()) {
products.value = []
return
}
loading.value = true
error.value = null
try {
const query = `name=~${searchQuery.value.trim()}`
const result = await useFetchJson(
`/api/v1/restricted/list-products/get-listing?${query}`
)
products.value = result.items || result
} catch (e) {
error.value = 'Failed to load products'
} finally {
loading.value = false
}
}
const { sortField, filters } = useTableState()
const debouncedFetch = debounce(fetchProducts, 400)
watch(searchQuery, () => {
watch([searchQuery, searchByReference], () => {
debouncedFetch()
})
const route = useRoute()
const router = useRouter()
const sortField = computed({
get: () => [
route.query.sort as string | undefined,
route.query.direction as 'asc' | 'desc' | undefined
],
set: ([sort]: [string, 'asc' | 'desc']) => {
const query = { ...route.query, sort, direction: 'asc' }
router.push({ query })
}
})
function getIcon(name: string) {
if (sortField.value[0] === name) {
return sortField.value[1] === 'asc'
? 'i-lucide-arrow-up-narrow-wide'
: 'i-lucide-arrow-down-wide-narrow'
}
return 'i-lucide-arrow-up-down'
}
const UInputNumber = resolveComponent('UInputNumber')
const UInput = resolveComponent('UInput')
const UButton = resolveComponent('UButton')
const UIcon = resolveComponent('UIcon')
function getIcon(name: string) {
if (sortField.value[0] === name) {
if (sortField.value[1] === 'asc') return 'i-lucide-arrow-up-narrow-wide'
if (sortField.value[1] === 'desc') return 'i-lucide-arrow-down-wide-narrow'
}
return 'i-lucide-arrow-up-down'
}
const updateFilter = debounce((columnId: string, val: string) => {
const newFilters = { ...filters.value }
if (val) newFilters[columnId] = val
else delete newFilters[columnId]
filters.value = newFilters
}, 400)
const columns: TableColumn<Product>[] = [
{
id: 'expand',
cell: ({ row }) =>
h(UButton, {
color: 'neutral',
variant: 'ghost',
icon: 'i-lucide-chevron-down',
square: true,
'aria-label': 'Expand',
ui: {
leadingIcon: [
'transition-transform',
row.getIsExpanded() ? 'duration-200 rotate-180' : ''
]
},
onClick: () => row.toggleExpanded()
})
},
{
accessorKey: 'product_id',
header: 'ID',
cell: ({ row }) => `#${row.getValue('product_id')}`
header: ({ column }) => {
return h('div', { class: 'flex flex-col gap-1' }, [
h('div', {
class: 'flex items-center gap-2 cursor-pointer',
onClick: () => {
sortField.value = ['product_id', 'asc']
}
}, [
h('span', 'ID'),
h(UIcon, {
name: getIcon('product_id')
})
]),
h(UInput, {
placeholder: 'Search...',
modelValue: filters.value[column.id] ?? '',
'onUpdate:modelValue': (val: string) => {
updateFilter(column.id, val)
},
size: 'xs'
})
])
},
cell: ({ row }) => `#${row.getValue('product_id') as number}`
},
{
accessorKey: 'image_link',
header: 'Image',
cell: ({ row }) =>
h('img', {
src: row.getValue('image_link'),
style: 'width:40px;height:40px;object-fit:cover;',
onError: (e: Event) => {
(e.target as HTMLImageElement).src = errorImg
}
cell: ({ row }) => {
return h('img', {
src: row.getValue('image_link') as string,
style: 'width:40px;height:40px;object-fit:cover;'
})
}
},
{
accessorKey: 'name',
header: 'Name',
cell: ({ row }) => row.getValue('name')
header: ({ column }) => {
return h('div', { class: 'flex flex-col gap-1' }, [
h('div', {
class: 'flex items-center gap-2 cursor-pointer',
onClick: () => {
sortField.value = ['name', 'asc']
}
}, [
h('span', 'Name'),
h(UIcon, {
name: getIcon('name')
})
]),
h(UInput, {
placeholder: 'Search...',
modelValue: filters.value[column.id] ?? '',
'onUpdate:modelValue': (val: string) => {
updateFilter(column.id, val)
},
size: 'xs'
})
])
},
cell: ({ row }) => row.getValue('name') as string,
filterFn: (row, columnId, value) => {
const name = row.getValue(columnId) as string
return name.toLowerCase().includes(value.toLowerCase())
}
},
{
accessorKey: 'quantity',
header: 'In stock',
cell: ({ row }) => row.getValue('quantity')
header: ({ column }) => {
return h('div', { class: 'flex flex-col gap-1' }, [
h('div', {
class: 'flex items-center gap-2 cursor-pointer',
onClick: () => {
sortField.value = ['quantity', 'asc']
}
}, [
h('span', 'In stock'),
h(UIcon, {
name: getIcon('quantity')
})
]),
])
},
cell: ({ row }) => row.getValue('quantity') as number
},
{
accessorKey: 'action',
header: '',
cell: ({ row }) =>
h(
UButton,
{
onClick: () =>
router.push({
name: 'admin-product-details',
params: {
product_id: row.original.product_id,
link_rewrite: row.original.link_rewrite
}
}),
color: 'info',
variant: 'soft'
accessorKey: 'count',
header: 'Count',
cell: ({ row }) => {
return h(UInputNumber, {
modelValue: selectedCount.value.product_id === row.original.product_id ? selectedCount.value.count : 0,
'onUpdate:modelValue': (val: number) => {
if (val)
selectedCount.value = {
product_id: row.original.product_id,
count: val
}
else {
selectedCount.value = {
product_id: null,
count: 0
}
}
},
() => 'Show product'
)
min: 0,
max: row.original.quantity
})
}
},
{
accessorKey: 'count',
header: '',
cell: ({ row }) => {
return h(UButton, {
onClick: () => {
addToCart(row.original.product_id)
},
color: selectedCount.value.product_id !== row.original.product_id ? 'info' : 'primary',
variant: 'solid'
}, 'Add to cart')
},
},
{
accessorKey: 'count',
header: '',
cell: ({ row }) => {
return h(UButton, {
onClick: () => {
goToProduct(row.original.product_id)
},
class: 'cursor-pointer',
color: 'info',
variant: 'soft'
}, () => 'Show product')
},
},
{
accessorKey: 'counta',
header: '',
cell: ({ row }) => {
return h(UIcon, {
onClick: () => toggleFavorite(row.original),
class: [
'cursor-pointer text-[20px] transition-transform duration-200 hover:scale-125',
row.original.is_favorite ? 'text-red-500' : 'text-blue-500'
],
name: 'material-symbols:favorite',
variant: 'soft',
})
}
}
]
const columnsChild: TableColumn<Product>[] = [
{
accessorKey: 'product_id',
header: '',
cell: ({ row }) => `#${row.getValue('product_id') as number}`
},
{
accessorKey: 'image_link',
header: '',
cell: ({ row }) => {
return h('img', {
src: row.getValue('image_link') as string,
style: 'width:40px;height:40px;object-fit:cover;'
})
}
},
{
accessorKey: 'name',
header: '',
cell: ({ row }) => row.getValue('name') as string
},
{
accessorKey: 'quantity',
header: '',
cell: ({ row }) => row.getValue('quantity') as number
},
{
accessorKey: 'count',
header: '',
cell: ({ row }) => {
return h(UInputNumber, {
modelValue: selectedCount.value.product_id === row.original.product_id ? selectedCount.value.count : 0,
'onUpdate:modelValue': (val: number) => {
if (val)
selectedCount.value = {
product_id: row.original.product_id,
count: val
}
else {
selectedCount.value = {
product_id: null,
count: 0
}
}
},
min: 0,
max: row.original.quantity
})
}
},
{
accessorKey: 'count',
header: '',
cell: ({ row }) => {
return h(UButton, {
onClick: () => {
addToCart(row.original.product_id)
},
color: selectedCount.value.product_id !== row.original.product_id ? 'info' : 'primary',
disabled: selectedCount.value.product_id !== row.original.product_id,
variant: 'solid'
}, 'Add to cart')
},
},
{
accessorKey: 'count',
header: '',
cell: ({ row }) => {
return h(UButton, {
onClick: () => {
goToProduct(row.original.product_id)
},
class: 'cursor-pointer',
color: 'info',
variant: 'soft'
}, () => 'Show product')
},
},
{
accessorKey: 'counta',
header: '',
cell: ({ row }) => {
return h(UIcon, {
onClick: () => toggleFavorite(row.original),
class: [
'cursor-pointer text-[20px] transition-transform duration-200 hover:scale-125',
row.original.is_favorite ? 'text-red-500' : 'text-blue-500'
],
name: 'material-symbols:favorite',
variant: 'soft',
})
}
}
]
import { useCustomerProductStore } from '@/stores/customer/customer-product'
const customerProductStore = useCustomerProductStore()
function toggleFavorite(product: Product) {
customerProductStore.toggleFavorite(product)
}
</script>
<style scoped>

View File

@@ -0,0 +1,32 @@
import { ref, watch } from 'vue'
export function useDebouncedSearch<T>(fetchFn: () => Promise<void>, delay = 400) {
const loading = ref(false)
function debounce<T extends (...args: any[]) => any>(fn: T, delay: number) {
let t: ReturnType<typeof setTimeout> | null = null
return (...args: Parameters<T>) => {
if (t) clearTimeout(t)
t = setTimeout(() => fn(...args), delay)
}
}
const debouncedFetch = debounce(fetchFn, delay)
watch(() => { }, () => {
loading.value = false
}, { immediate: true })
return {
loading,
debouncedFetch
}
}
export function debounce<T extends (...args: any[]) => any>(fn: T, delay: number): (...args: Parameters<T>) => void {
let t: ReturnType<typeof setTimeout> | null = null
return (...args: Parameters<T>) => {
if (t) clearTimeout(t)
t = setTimeout(() => fn(...args), delay)
}
}

View File

@@ -0,0 +1,109 @@
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/customer/cart'
import { useCustomerProductStore } from '@/stores/customer/customer-product'
import { useToast } from '@nuxt/ui/runtime/composables/useToast.js'
import { useFetchJson } from '@/composable/useFetchJson'
export interface SearchProductParams {
query: string
searchByReference?: boolean
}
export function useProductSearchApi() {
const router = useRouter()
const cartStore = useCartStore()
const customerProductStore = useCustomerProductStore()
const toast = useToast()
const searchQuery = ref('')
const products = ref<any[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const searchByReference = ref(false)
const selectedCount = ref({
product_id: null as number | null,
count: 0
})
async function fetchProducts() {
if (!searchQuery.value.trim()) {
products.value = []
return
}
loading.value = true
error.value = null
try {
let query = ''
if (searchByReference.value) {
query = `reference_eq=${searchQuery.value.trim()}`
} else {
query = `name=~${searchQuery.value.trim()}`
}
const result = await useFetchJson(
`/api/v1/restricted/product/list?elems=30&${query}`
)
products.value = result.items || []
} catch (e) {
error.value = 'Failed to load products'
} finally {
loading.value = false
}
}
async function addToCart(product_id: number) {
if (!cartStore.activeCartId) {
toast.add({
title: "No cart selected",
description: "Please select a cart before adding products",
icon: "i-heroicons-exclamation-triangle",
duration: 5000
})
return
}
const count = selectedCount.value.count || 1
await cartStore.addProduct(product_id, count)
toast.add({
title: "Product added to cart",
description: `Quantity: ${count}`,
icon: "i-heroicons-check-circle",
duration: 5000
})
}
function goToProduct(productId: number) {
router.push({
name: 'customer-product-details',
params: { product_id: productId }
})
}
function getSortIcon(field: string, sortValue: [string | undefined, string | undefined]): string {
if (sortValue[0] === field) {
if (sortValue[1] === 'asc') return 'i-lucide-arrow-up-narrow-wide'
if (sortValue[1] === 'desc') return 'i-lucide-arrow-down-wide-narrow'
}
return 'i-lucide-arrow-up-down'
}
return {
searchQuery,
products,
loading,
error,
searchByReference,
selectedCount,
fetchProducts,
addToCart,
goToProduct,
getSortIcon
}
}

View File

@@ -0,0 +1,82 @@
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
export function useTableState() {
const route = useRoute()
const router = useRouter()
const page = computed({
get: () => Number(route.query.page) || 1,
set: (val: number) => {
router.push({
query: {
...route.query,
page: val
}
})
}
})
const sortField = computed({
get: () => [
route.query.sort as string | undefined,
route.query.direction as 'asc' | 'desc' | undefined
],
set: ([sort]: [string, 'asc' | 'desc']) => {
const currentSort = route.query.sort as string | undefined
const currentDirection = route.query.direction as 'asc' | 'desc' | undefined
let query = { ...route.query }
if (currentSort === sort) {
if (currentDirection === 'asc') {
query.direction = 'desc'
} else if (currentDirection === 'desc') {
delete query.sort
delete query.direction
} else {
query.direction = 'asc'
query.sort = sort
}
} else {
query.sort = sort
query.direction = 'asc'
}
router.push({ query })
}
})
const filters = computed<Record<string, string>>({
get: () => {
const q = { ...route.query }
delete q.page
delete q.sort
delete q.direction
return q as Record<string, string>
},
set: (val) => {
const baseQuery = { ...route.query }
Object.keys(baseQuery).forEach(key => {
if (!['page', 'sort', 'direction'].includes(key)) {
delete baseQuery[key]
}
})
router.push({
query: {
...baseQuery,
...val,
page: 1
}
})
}
})
return {
page,
sortField,
filters
}
}

View File

@@ -75,7 +75,7 @@ async function addNewCart(name: string) {
try {
const res = await useFetchJson<ApiResponse>(
`/api/v1/restricted/carts/add-product-to-cart?cart_id=${activeCartId.value}&product_id=${product_id}&amount=${count}`
`/api/v1/restricted/carts/add-product-to-cart?cart_id=${activeCartId.value}&product_id=${product_id}&amount=${count}&set_amount=false`
)
console.log('fsdfsdfdsfdsfs', res)

View File

@@ -33,30 +33,26 @@ export const useCustomerProductStore = defineStore('customer-product', () => {
const total = ref(0)
const perPage = ref(15)
async function fetchProductList() {
async function fetchProductList(paramsObj: Record<string, any>) {
loading.value = true
error.value = null
const params = new URLSearchParams()
Object.entries(route.query).forEach(([key, value]) => {
Object.entries(paramsObj).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