Implement unified catalog search with token-based filtering
All checks were successful
Build Docker Image / build (push) Successful in 3m23s

- Add useCatalogSearch composable for managing unified search state
- Add UnifiedSearchBar component with token chips for filters
- Add CatalogHero component for empty/landing state
- Create grid components for each display mode:
  - CatalogGridProducts, CatalogGridSuppliers, CatalogGridHubs
  - CatalogGridHubsForProduct, CatalogGridProductsFromSupplier
  - CatalogGridProductsInHub, CatalogGridOffers
- Add unified catalog page at /catalog with query params
- Remove SubNavigation from catalog section (kept for other sections)
- Update all links to use new unified catalog paths
- Delete old nested catalog pages (offers/suppliers/hubs flows)
- Add i18n translations for catalog section
This commit is contained in:
Ruslan Bakiev
2026-01-22 10:57:30 +07:00
parent 01f0836173
commit 08d7e0ade9
39 changed files with 1278 additions and 2185 deletions

View File

@@ -1,356 +0,0 @@
<template>
<Stack gap="0">
<!-- Loading -->
<Section v-if="isLoading" variant="plain" paddingY="lg">
<Stack align="center" justify="center" gap="4">
<Spinner />
<Text tone="muted">{{ t('catalogProductHubs.states.loading') }}</Text>
</Stack>
</Section>
<!-- Error / Not Found -->
<Section v-else-if="!hub || !product" variant="plain" paddingY="lg">
<Card padding="lg">
<Stack align="center" gap="4">
<IconCircle tone="primary">
<Icon name="lucide:package-x" size="24" />
</IconCircle>
<Heading :level="2">{{ t('catalogProductHubs.calculation.not_found.title') }}</Heading>
<Text tone="muted">{{ t('catalogProductHubs.calculation.not_found.subtitle') }}</Text>
<Button @click="navigateTo(localePath(`/catalog/offers/${productId}`))">
{{ t('catalogProductHubs.actions.back_to_hubs') }}
</Button>
</Stack>
</Card>
</Section>
<!-- Content -->
<template v-else>
<CatalogPage
:items="sources"
:loading="isLoadingRoutes"
:with-map="true"
map-id="offers-product-hub-sources-map"
point-color="#10b981"
v-model:selected-id="selectedSourceUuid"
:hovered-id="hoveredSourceUuid"
@update:hovered-id="hoveredSourceUuid = $event"
>
<template #searchBar>
<CatalogSearchBar
:active-filters="navigationFilters"
:show-counter="false"
@remove-filter="handleRemoveFilter"
/>
</template>
<template #header>
<Text v-if="sources.length === 0 && !isLoadingRoutes" tone="muted">Нет доступных источников</Text>
<Stack v-else gap="4">
<Text v-if="sources.length > 0" tone="muted">Выберите источник</Text>
<Card padding="md">
<div class="h-48">
<ClientOnly>
<apexchart
type="area"
height="180"
:options="chartOptions"
:series="chartSeries"
/>
</ClientOnly>
</div>
</Card>
</Stack>
</template>
<template #card="{ item }">
<OfferResultCard
:location-name="getOfferData(item.uuid)?.locationName"
:product-name="product.name"
:price-per-unit="getOfferData(item.uuid)?.pricePerUnit"
:currency="getOfferData(item.uuid)?.currency"
:unit="getOfferData(item.uuid)?.unit"
:stages="item.stages"
:start-name="item.name"
:end-name="hub?.name"
:kyc-profile-uuid="getOfferData(item.uuid)?.kycProfileUuid"
@select="navigateTo(localePath(`/catalog/offers/detail/${item.uuid}`))"
/>
</template>
<template #empty>
<Stack align="center" gap="2">
<Icon name="lucide:truck" size="32" class="text-base-content/40" />
<Text tone="muted">{{ t('catalogProductHubs.calculation.empty') }}</Text>
</Stack>
</template>
</CatalogPage>
</template>
</Stack>
</template>
<script setup lang="ts">
import { GetNodeConnectionsDocument, GetOffersByHubDocument } from '~/composables/graphql/public/geo-generated'
import { GetAvailableProductsDocument, GetOfferDocument, GetSupplierProfileByTeamDocument } from '~/composables/graphql/public/exchange-generated'
definePageMeta({
layout: 'topnav'
})
const route = useRoute()
const localePath = useLocalePath()
const { t } = useI18n()
const { execute } = useGraphQL()
const isLoading = ref(true)
const isLoadingRoutes = ref(false)
const hub = ref<any>(null)
const product = ref<{ uuid: string; name: string } | null>(null)
const selectedSourceUuid = ref('')
const hoveredSourceUuid = ref<string>()
const rawSources = ref<any[]>([])
const offersData = ref<Map<string, any>>(new Map())
const suppliersData = ref<Map<string, any>>(new Map())
const productId = computed(() => route.params.productId as string)
const hubId = computed(() => route.params.hubId as string)
const quantity = computed(() => route.query.quantity as string | undefined)
// Navigation filters for search bar badges
const navigationFilters = computed(() => {
const filters: Array<{ id: string; label: string; key: string }> = []
if (product.value?.name) {
filters.push({
id: 'product',
key: 'Товар',
label: product.value.name
})
}
if (hub.value?.name) {
filters.push({
id: 'hub',
key: 'Хаб',
label: hub.value.name
})
}
if (quantity.value) {
filters.push({
id: 'quantity',
key: 'Кол-во',
label: `${quantity.value} т`
})
}
return filters
})
// Handle removing navigation filter (navigate back)
const handleRemoveFilter = (filterId: string) => {
if (filterId === 'hub') {
navigateTo(localePath(`/catalog/offers/${productId.value}`))
} else if (filterId === 'product') {
navigateTo(localePath('/catalog/offers'))
} else if (filterId === 'quantity') {
// Remove quantity from query, stay on same page
navigateTo({ path: route.path, query: {} })
}
}
// Mock price history generator (seeded by uuid for consistent results)
const getMockPriceHistory = (uuid: string): number[] => {
const seed = uuid.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
const basePrice = 100 + (seed % 200)
return Array.from({ length: 30 }, (_, i) => {
const variation = Math.sin(seed + i * 0.3) * 30 + Math.cos(seed * 0.2 + i) * 15
return Math.round(basePrice + variation)
})
}
// Chart configuration
const priceHistory = computed(() => getMockPriceHistory(productId.value))
const trend = computed(() => {
if (priceHistory.value.length < 2) return 0
const first = priceHistory.value[0]
const last = priceHistory.value[priceHistory.value.length - 1]
if (!first || first === 0) return 0
return Math.round(((last - first) / first) * 100)
})
const chartOptions = computed(() => ({
chart: {
type: 'area',
toolbar: { show: false },
animations: { enabled: true }
},
stroke: { curve: 'smooth', width: 2 },
fill: {
type: 'gradient',
gradient: { shadeIntensity: 1, opacityFrom: 0.4, opacityTo: 0.1 }
},
colors: [trend.value >= 0 ? '#22c55e' : '#ef4444'],
dataLabels: { enabled: false },
xaxis: {
categories: priceHistory.value.map((_, i) => `${i + 1}`),
labels: { show: false }
},
yaxis: { labels: { formatter: (val: number) => `$${val}` } },
tooltip: { y: { formatter: (val: number) => `$${val}` } },
grid: { borderColor: '#e5e7eb', strokeDashArray: 4 }
}))
const chartSeries = computed(() => [{
name: t('catalogProductHubs.chart.price'),
data: priceHistory.value
}])
// Transform sources for CatalogPage
const sources = computed(() => {
return rawSources.value.map(source => ({
uuid: source.sourceUuid || '',
name: source.sourceName || '',
latitude: source.sourceLat,
longitude: source.sourceLon,
distanceKm: source.distanceKm,
durationSeconds: source.routes?.[0]?.totalTimeSeconds,
stages: (source.routes?.[0]?.stages || []).map((stage: any) => ({
transportType: stage?.transportType,
distanceKm: stage?.distanceKm
}))
}))
})
// Get offer data for card
const getOfferData = (uuid: string) => {
return offersData.value.get(uuid)
}
// Load offer details for prices and supplier info
const loadOfferDetails = async () => {
if (rawSources.value.length === 0) {
offersData.value.clear()
suppliersData.value.clear()
return
}
const newOffersData = new Map<string, any>()
const newSuppliersData = new Map<string, any>()
const teamUuidsToLoad = new Set<string>()
// First, load all offers
await Promise.all(rawSources.value.map(async (source) => {
try {
const data = await execute(GetOfferDocument, { uuid: source.sourceUuid }, 'public', 'exchange')
if (data?.getOffer) {
newOffersData.set(source.sourceUuid, data.getOffer)
if (data.getOffer.teamUuid) {
teamUuidsToLoad.add(data.getOffer.teamUuid)
}
}
} catch (error) {
console.error('Error loading offer:', source.sourceUuid, error)
}
}))
// Then, load supplier profiles for KYC
await Promise.all([...teamUuidsToLoad].map(async (teamUuid) => {
try {
const data = await execute(GetSupplierProfileByTeamDocument, { teamUuid }, 'public', 'exchange')
if (data?.getSupplierProfileByTeam) {
newSuppliersData.set(teamUuid, data.getSupplierProfileByTeam)
}
} catch (error) {
console.error('Error loading supplier:', teamUuid, error)
}
}))
// Merge kycProfileUuid into offer data
newOffersData.forEach((offer, offerUuid) => {
if (offer.teamUuid) {
const supplier = newSuppliersData.get(offer.teamUuid)
if (supplier?.kycProfileUuid) {
offer.kycProfileUuid = supplier.kycProfileUuid
}
}
})
offersData.value = newOffersData
suppliersData.value = newSuppliersData
}
// Load offers with routes to this hub
const loadRoutes = async () => {
if (!productId.value || !hubId.value) {
rawSources.value = []
offersData.value.clear()
return
}
isLoadingRoutes.value = true
selectedSourceUuid.value = ''
try {
const data = await execute(
GetOffersByHubDocument,
{
hubUuid: hubId.value,
productUuid: productId.value,
limit: 12
},
'public',
'geo'
)
rawSources.value = (data?.offersByHub || []).filter(Boolean)
await loadOfferDetails()
} catch (error) {
console.error('Error loading offers:', error)
rawSources.value = []
} finally {
isLoadingRoutes.value = false
}
}
// Initial load
try {
const [{ data: hubData }, { data: productsData }] = await Promise.all([
useServerQuery('hub-info', GetNodeConnectionsDocument, { uuid: hubId.value }, 'public', 'geo'),
useServerQuery('available-products', GetAvailableProductsDocument, {}, 'public', 'exchange')
])
hub.value = hubData.value?.nodeConnections?.hub || null
const products = (productsData.value?.getAvailableProducts || [])
.filter((p): p is { uuid: string; name: string } => p !== null && !!p.uuid && !!p.name)
product.value = products.find(p => p.uuid === productId.value) || null
// Load routes after initial data
if (product.value && hub.value) {
await loadRoutes()
}
} catch (error) {
console.error('Error loading data:', error)
} finally {
isLoading.value = false
}
// SEO
useHead(() => ({
title: product.value?.name && hub.value?.name
? `${product.value.name} - ${hub.value.name}`
: t('catalogProductHubs.meta.title'),
meta: [
{
name: 'description',
content: t('catalogProductHubs.calculation.meta.description', {
product: product.value?.name || '',
hub: hub.value?.name || '',
offers: sources.value.length
})
}
]
}))
</script>

View File

@@ -1,158 +0,0 @@
<template>
<CatalogPage
:items="filteredHubs"
:loading="isLoading"
:total-count="hubs.length"
:grid-columns="3"
with-map
use-server-clustering
cluster-node-type="logistics"
map-id="offers-product-hubs-map"
point-color="#10b981"
:hovered-id="hoveredId"
@select="onSelectHub"
@update:hovered-id="hoveredId = $event"
>
<template #searchBar="{ displayedCount, totalCount }">
<CatalogSearchBar
v-model:search-query="searchQuery"
:active-filters="navigationFilters"
:displayed-count="displayedCount"
:total-count="totalCount"
@remove-filter="handleRemoveFilter"
/>
</template>
<template #header>
<Text v-if="!isLoading && !product" tone="muted">Товар не найден</Text>
<Text v-else-if="!isLoading" tone="muted">Выберите хаб</Text>
</template>
<template #card="{ item }">
<HubCard
:hub="item"
:link-to="localePath(`/catalog/offers/${productId}/${item.uuid}`)"
/>
</template>
<template #empty>
<Stack align="center" gap="2">
<Icon name="lucide:map-pin-off" size="32" class="text-base-content/40" />
<Text tone="muted">{{ t('catalogProductHubs.empty.no_hubs') }}</Text>
</Stack>
</template>
</CatalogPage>
</template>
<script setup lang="ts">
import { GetOffersByProductDocument, GetHubsNearOfferDocument } from '~/composables/graphql/public/geo-generated'
definePageMeta({
layout: 'topnav'
})
const route = useRoute()
const localePath = useLocalePath()
const { t } = useI18n()
const isLoading = ref(true)
const hoveredId = ref<string>()
const product = ref<{ uuid: string; name: string } | null>(null)
const hubs = ref<Array<{ uuid: string; name: string; latitude?: number; longitude?: number; country?: string; countryCode?: string }>>([])
const productId = computed(() => route.params.productId as string)
// Navigation filters for search bar badges
const navigationFilters = computed(() => {
const filters: Array<{ id: string; label: string; key: string }> = []
if (product.value?.name) {
filters.push({
id: 'product',
key: 'Товар',
label: product.value.name
})
}
return filters
})
// Handle removing navigation filter (navigate back)
const handleRemoveFilter = (filterId: string) => {
if (filterId === 'product') {
navigateTo(localePath('/catalog/offers'))
}
}
// Search
const searchQuery = ref('')
const filteredHubs = computed(() => {
if (!searchQuery.value.trim()) return hubs.value
const q = searchQuery.value.toLowerCase()
return hubs.value.filter(hub =>
hub.name?.toLowerCase().includes(q) ||
hub.country?.toLowerCase().includes(q)
)
})
// Handle hub selection
const onSelectHub = (hub: any) => {
navigateTo(localePath(`/catalog/offers/${productId.value}/${hub.uuid}`))
}
// Initial load
try {
// Get offers for this product from geo
const { data: offersData } = await useServerQuery(
'offers-for-product',
GetOffersByProductDocument,
{ productUuid: productId.value },
'public',
'geo'
)
const offers = offersData.value?.offersByProduct || []
if (offers.length > 0) {
const firstOffer = offers[0]
product.value = {
uuid: productId.value,
name: firstOffer?.productName || ''
}
// Get hubs near the first offer's location
if (firstOffer?.uuid) {
const { data: hubsData } = await useServerQuery(
'hubs-near-offer',
GetHubsNearOfferDocument,
{ offerUuid: firstOffer.uuid, limit: 12 },
'public',
'geo'
)
hubs.value = (hubsData.value?.hubsNearOffer || [])
.filter((h): h is NonNullable<typeof h> => h !== null && !!h.uuid && !!h.name)
.map(h => ({
uuid: h.uuid!,
name: h.name!,
latitude: h.latitude ?? undefined,
longitude: h.longitude ?? undefined,
country: h.country || undefined,
countryCode: h.countryCode || undefined
}))
}
}
} catch (error) {
console.error('Error loading product hubs:', error)
} finally {
isLoading.value = false
}
// SEO
useHead(() => ({
title: product.value?.name
? t('catalogProductHubs.meta.title_with_name', { name: product.value.name })
: t('catalogProductHubs.meta.title')
}))
</script>

View File

@@ -1,85 +0,0 @@
<template>
<CatalogPage
:items="filteredProducts"
:loading="isLoading"
:total-count="products.length"
:grid-columns="3"
with-map
use-server-clustering
cluster-node-type="offer"
map-id="offers-products-map"
point-color="#22c55e"
:hovered-id="hoveredId"
@update:hovered-id="hoveredId = $event"
>
<template #searchBar>
<CatalogSearchBar
v-model:search-query="searchQuery"
:show-counter="false"
/>
</template>
<template #header>
<Text v-if="!isLoading" tone="muted">Выберите товар</Text>
</template>
<template #card="{ item }">
<HubProductCard
:name="item.name || ''"
:price-history="getMockPriceHistory(item.uuid)"
@select="goToProduct(item.uuid)"
/>
</template>
<template #empty>
<Text tone="muted">{{ t('catalogProducts.empty.subtitle') }}</Text>
</template>
</CatalogPage>
</template>
<script setup lang="ts">
definePageMeta({
layout: 'topnav'
})
const localePath = useLocalePath()
const { t } = useI18n()
const { items: products, isLoading, init } = useCatalogProducts()
// Hover state
const hoveredId = ref<string>()
// Search
const searchQuery = ref('')
const filteredProducts = computed(() => {
if (!searchQuery.value.trim()) return products.value
const q = searchQuery.value.toLowerCase()
return products.value.filter(item =>
item.name?.toLowerCase().includes(q)
)
})
// Navigate to product detail
const goToProduct = (productId: string) => {
navigateTo(localePath(`/catalog/offers/${productId}`))
}
// Mock price history generator (seeded by uuid for consistent results)
const getMockPriceHistory = (uuid: string): number[] => {
const seed = uuid.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
const basePrice = 100 + (seed % 200)
return Array.from({ length: 7 }, (_, i) => {
const variation = Math.sin(seed + i * 0.5) * 20 + Math.cos(seed * 0.3 + i) * 10
return Math.round(basePrice + variation)
})
}
// Initialize
await init()
useHead(() => ({
title: t('catalogProducts.header.title')
}))
</script>