feat(catalog): implement step-by-step navigation for offers and suppliers
All checks were successful
Build Docker Image / build (push) Successful in 4m49s

- Transform offers/index.vue to show products list with sparkline charts
- Create nested routes for offers: /offers → /offers/[productId] → /offers/[productId]/[hubId]
- Create nested routes for suppliers: /suppliers → /suppliers/[supplierId] → /suppliers/[supplierId]/[productId] → /suppliers/[supplierId]/[productId]/[hubId]
- Add OffersBreadcrumbs and SuppliersBreadcrumbs components for navigation
- Update HubCard to accept custom linkTo prop
- Key difference: Suppliers calculation uses FindRoutes (single source), Offers uses FindProductRoutes (all sources)
This commit is contained in:
Ruslan Bakiev
2026-01-16 00:52:47 +07:00
parent 210d3e935c
commit 1e87a14065
10 changed files with 1451 additions and 413 deletions

View File

@@ -1,7 +1,7 @@
<template> <template>
<component <component
:is="linkable ? NuxtLink : 'div'" :is="linkable ? NuxtLink : 'div'"
:to="linkable ? localePath(`/catalog/hubs/${hub.uuid}`) : undefined" :to="linkable ? resolvedLink : undefined"
class="block" class="block"
:class="{ 'cursor-pointer': selectable }" :class="{ 'cursor-pointer': selectable }"
@click="selectable && $emit('select')" @click="selectable && $emit('select')"
@@ -47,6 +47,7 @@ const props = defineProps<{
hub: Hub hub: Hub
selectable?: boolean selectable?: boolean
isSelected?: boolean isSelected?: boolean
linkTo?: string
}>() }>()
defineEmits<{ defineEmits<{
@@ -57,7 +58,8 @@ defineEmits<{
const localePath = useLocalePath() const localePath = useLocalePath()
const { t } = useI18n() const { t } = useI18n()
const linkable = computed(() => !props.selectable && props.hub.uuid) const linkable = computed(() => !props.selectable && (props.linkTo || props.hub.uuid))
const resolvedLink = computed(() => props.linkTo || localePath(`/catalog/hubs/${props.hub.uuid}`))
// ISO code to emoji flag // ISO code to emoji flag
const isoToEmoji = (code: string): string => { const isoToEmoji = (code: string): string => {

View File

@@ -0,0 +1,51 @@
<template>
<div class="breadcrumbs text-sm">
<ul>
<li v-for="(crumb, index) in breadcrumbs" :key="index">
<NuxtLink v-if="crumb.to" :to="crumb.to" class="hover:text-primary">
{{ crumb.label }}
</NuxtLink>
<span v-else class="text-base-content">{{ crumb.label }}</span>
</li>
</ul>
</div>
</template>
<script setup lang="ts">
const props = defineProps<{
productId?: string
productName?: string
hubId?: string
hubName?: string
}>()
const localePath = useLocalePath()
const { t } = useI18n()
const breadcrumbs = computed(() => {
const crumbs: Array<{ label: string; to?: string }> = []
// Products list
crumbs.push({
label: t('breadcrumbs.products', 'Products'),
to: localePath('/catalog/offers')
})
// Product
if (props.productId) {
crumbs.push({
label: props.productName || `#${props.productId.slice(0, 8)}...`,
to: props.hubId ? localePath(`/catalog/offers/${props.productId}`) : undefined
})
}
// Hub
if (props.hubId) {
crumbs.push({
label: props.hubName || `#${props.hubId.slice(0, 8)}...`
})
}
return crumbs
})
</script>

View File

@@ -0,0 +1,63 @@
<template>
<div class="breadcrumbs text-sm">
<ul>
<li v-for="(crumb, index) in breadcrumbs" :key="index">
<NuxtLink v-if="crumb.to" :to="crumb.to" class="hover:text-primary">
{{ crumb.label }}
</NuxtLink>
<span v-else class="text-base-content">{{ crumb.label }}</span>
</li>
</ul>
</div>
</template>
<script setup lang="ts">
const props = defineProps<{
supplierId?: string
supplierName?: string
productId?: string
productName?: string
hubId?: string
hubName?: string
}>()
const localePath = useLocalePath()
const { t } = useI18n()
const breadcrumbs = computed(() => {
const crumbs: Array<{ label: string; to?: string }> = []
// Suppliers list
crumbs.push({
label: t('breadcrumbs.suppliers', 'Suppliers'),
to: localePath('/catalog/suppliers')
})
// Supplier
if (props.supplierId) {
const hasNext = props.productId
crumbs.push({
label: props.supplierName || `#${props.supplierId.slice(0, 8)}...`,
to: hasNext ? localePath(`/catalog/suppliers/${props.supplierId}`) : undefined
})
}
// Product
if (props.productId) {
const hasNext = props.hubId
crumbs.push({
label: props.productName || `#${props.productId.slice(0, 8)}...`,
to: hasNext ? localePath(`/catalog/suppliers/${props.supplierId}/${props.productId}`) : undefined
})
}
// Hub
if (props.hubId) {
crumbs.push({
label: props.hubName || `#${props.hubId.slice(0, 8)}...`
})
}
return crumbs
})
</script>

View File

@@ -0,0 +1,301 @@
<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"
>
<template #header>
<Stack gap="3">
<!-- Breadcrumbs -->
<OffersBreadcrumbs
:product-id="productId"
:product-name="product.name"
:hub-id="hubId"
:hub-name="hub.name"
/>
<!-- Product info -->
<div>
<Heading :level="1">{{ product.name }}</Heading>
<Text tone="muted" size="sm">{{ t('catalogProductHubs.calculation.destination') }}: {{ hub.name }}, {{ hub.country }}</Text>
</div>
<!-- Price chart -->
<Card padding="md">
<Stack gap="2">
<Text weight="semibold" size="sm">{{ t('catalogProductHubs.chart.title') }}</Text>
<div class="h-48">
<ClientOnly>
<apexchart
type="area"
height="180"
:options="chartOptions"
:series="chartSeries"
/>
</ClientOnly>
</div>
</Stack>
</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"
/>
</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, FindProductRoutesDocument } from '~/composables/graphql/public/geo-generated'
import { GetAvailableProductsDocument, GetOfferDocument } 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 rawSources = ref<any[]>([])
const offersData = ref<Map<string, any>>(new Map())
const productId = computed(() => route.params.productId as string)
const hubId = computed(() => route.params.hubId as string)
// 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
const loadOfferDetails = async () => {
if (rawSources.value.length === 0) {
offersData.value.clear()
return
}
const newOffersData = new Map<string, any>()
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)
}
} catch (error) {
console.error('Error loading offer:', source.sourceUuid, error)
}
}))
offersData.value = newOffersData
}
// Load routes
const loadRoutes = async () => {
if (!productId.value || !hubId.value) {
rawSources.value = []
offersData.value.clear()
return
}
isLoadingRoutes.value = true
selectedSourceUuid.value = ''
try {
const data = await execute(
FindProductRoutesDocument,
{
productUuid: productId.value,
toUuid: hubId.value,
limitSources: 12,
limitRoutes: 1
},
'public',
'geo'
)
rawSources.value = (data?.findProductRoutes || []).filter(Boolean)
await loadOfferDetails()
} catch (error) {
console.error('Error loading routes:', 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

@@ -0,0 +1,163 @@
<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>
<!-- Product Not Found -->
<Section v-else-if="!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.not_found.title') }}</Heading>
<Text tone="muted">{{ t('catalogProductHubs.not_found.subtitle') }}</Text>
<Button @click="navigateTo(localePath('/catalog/offers'))">
{{ t('catalogProductHubs.actions.back_to_products') }}
</Button>
</Stack>
</Card>
</Section>
<!-- Content -->
<Section v-else variant="plain" paddingY="lg">
<Stack gap="4">
<!-- Breadcrumbs -->
<OffersBreadcrumbs :product-id="productId" :product-name="product.name" />
<!-- Header -->
<div>
<Heading :level="1">{{ product.name }}</Heading>
<Text tone="muted" size="sm">{{ t('catalogProductHubs.header.subtitle', { count: hubs.length }) }}</Text>
</div>
<!-- Price chart -->
<Card padding="md">
<div class="h-48">
<ClientOnly>
<apexchart
type="area"
height="180"
:options="chartOptions"
:series="chartSeries"
/>
</ClientOnly>
</div>
</Card>
<!-- Hubs grid -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
<HubCard
v-for="hub in hubs"
:key="hub.uuid"
:hub="hub"
:link-to="localePath(`/catalog/offers/${productId}/${hub.uuid}`)"
/>
</div>
<!-- Empty state -->
<Stack v-if="hubs.length === 0" 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>
</Stack>
</Section>
</Stack>
</template>
<script setup lang="ts">
import { GetAvailableProductsDocument } from '~/composables/graphql/public/exchange-generated'
import { GetNodesDocument } from '~/composables/graphql/public/geo-generated'
definePageMeta({
layout: 'topnav'
})
const route = useRoute()
const localePath = useLocalePath()
const { t } = useI18n()
const isLoading = ref(true)
const product = ref<{ uuid: string; name: string } | null>(null)
const hubs = ref<Array<{ uuid: string; name: string; country?: string; countryCode?: string }>>([])
const productId = computed(() => route.params.productId as string)
// Mock price history generator
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) * 20 + Math.cos(seed * 0.2 + i) * 15
return Math.round(basePrice + variation)
})
}
const priceHistory = computed(() => product.value ? getMockPriceHistory(product.value.uuid) : [])
// Chart configuration
const chartOptions = computed(() => ({
chart: {
type: 'area',
sparkline: { enabled: false },
toolbar: { show: false },
animations: { enabled: false }
},
stroke: { curve: 'smooth', width: 2 },
fill: {
type: 'gradient',
gradient: { shadeIntensity: 1, opacityFrom: 0.4, opacityTo: 0.1 }
},
colors: ['#3b82f6'],
xaxis: {
labels: { show: false },
axisBorder: { show: false },
axisTicks: { show: false }
},
yaxis: { labels: { show: true } },
grid: { show: true, borderColor: '#e5e7eb', strokeDashArray: 4 },
tooltip: { enabled: true }
}))
const chartSeries = computed(() => [{
name: t('catalogProductHubs.chart.price'),
data: priceHistory.value
}])
// Initial load
try {
const [{ data: productsData }, { data: hubsData }] = await Promise.all([
useServerQuery('product-info', GetAvailableProductsDocument, {}, 'public', 'exchange'),
useServerQuery('all-hubs', GetNodesDocument, { limit: 100 }, 'public', 'geo')
])
const foundProduct = (productsData.value?.getAvailableProducts || [])
.find(p => p?.uuid === productId.value)
if (foundProduct) {
product.value = { uuid: foundProduct.uuid!, name: foundProduct.name || '' }
}
hubs.value = (hubsData.value?.nodes || [])
.filter((h): h is { uuid: string; name: string; country?: string; countryCode?: string } =>
h !== null && !!h.uuid && !!h.name
)
.map(h => ({ uuid: h.uuid!, name: h.name!, 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,179 +1,79 @@
<template> <template>
<CatalogPage <Stack gap="0">
:items="displayItems" <!-- Loading -->
:map-items="itemsWithCoords" <Section v-if="isLoading" variant="plain" paddingY="lg">
:loading="isLoading || productsLoading" <Stack align="center" justify="center" gap="4">
with-map <Spinner />
map-id="offers-map" <Text tone="muted">{{ t('catalogProducts.states.loading') }}</Text>
point-color="#f59e0b" </Stack>
:selected-id="selectedOfferId" </Section>
:hovered-id="hoveredOfferId"
:total-count="total" <!-- Empty -->
@select="onSelectOffer" <Section v-else-if="products.length === 0" variant="plain" paddingY="lg">
@update:hovered-id="hoveredOfferId = $event" <Card padding="lg">
> <Stack align="center" gap="4">
<template #searchBar="{ displayedCount, totalCount }"> <IconCircle tone="primary">
<CatalogSearchBar <Icon name="lucide:package" size="24" />
v-model:search-query="searchQuery" </IconCircle>
:active-filters="activeFilterBadges" <Heading :level="2">{{ t('catalogProducts.empty.title') }}</Heading>
:displayed-count="displayedCount" <Text tone="muted">{{ t('catalogProducts.empty.subtitle') }}</Text>
:total-count="totalCount" </Stack>
@remove-filter="onRemoveFilter" </Card>
@search="onSearch" </Section>
>
<template #filters> <!-- Content -->
<div class="p-2 space-y-3"> <Section v-else variant="plain" paddingY="lg">
<Stack gap="4">
<!-- Header -->
<div> <div>
<div class="text-xs font-semibold mb-1 text-base-content/70">{{ t('catalogOffersSection.filters.product') }}</div> <Heading :level="1">{{ t('catalogProducts.header.title') }}</Heading>
<ul class="menu menu-compact max-h-48 overflow-y-auto"> <Text tone="muted" size="sm">{{ t('catalogProducts.header.subtitle', { count: products.length }) }}</Text>
<li v-for="filter in productFilters" :key="filter.id">
<a
:class="{ 'active': (selectedProductUuid === filter.id || (!selectedProductUuid && filter.id === 'all')) }"
@click="onProductFilterChange(filter.id)"
>{{ filter.label }}</a>
</li>
</ul>
</div> </div>
</div>
</template>
</CatalogSearchBar>
</template>
<template #card="{ item }"> <!-- Products grid -->
<OfferCard :offer="item" /> <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
</template> <HubProductCard
v-for="product in products"
<template #pagination> :key="product.uuid"
<PaginationLoadMore :name="product.name || ''"
v-if="displayItems.length > 0" :price-history="getMockPriceHistory(product.uuid)"
:shown="displayItems.length" @select="goToProduct(product.uuid)"
:total="total"
:can-load-more="canLoadMore"
:loading="isLoadingMore"
hide-counter
@load-more="loadMore"
class="mt-4"
/> />
</template> </div>
</Stack>
<template #empty> </Section>
<Text tone="muted">{{ t('catalogOffersSection.empty.no_offers') }}</Text> </Stack>
</template>
</CatalogPage>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import type { MapBounds } from '~/components/catalog/CatalogMap.vue'
definePageMeta({ definePageMeta({
layout: 'topnav' layout: 'topnav'
}) })
const localePath = useLocalePath()
const { t } = useI18n() const { t } = useI18n()
// Products for filter const { items: products, isLoading, init } = useCatalogProducts()
const {
items: products,
isLoading: productsLoading,
init: initProducts
} = useCatalogProducts()
// Offers // Navigate to product detail
const { const goToProduct = (productId: string) => {
items, navigateTo(localePath(`/catalog/offers/${productId}`))
total, }
selectedProductUuid,
isLoading,
isLoadingMore,
canLoadMore,
loadMore,
init: initOffers,
setProductUuid
} = useCatalogOffers()
// Selected/hovered offer for map highlighting // Mock price history generator (seeded by uuid for consistent results)
const selectedOfferId = ref<string>() const getMockPriceHistory = (uuid: string): number[] => {
const hoveredOfferId = ref<string>() const seed = uuid.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
const basePrice = 100 + (seed % 200)
// Search bar return Array.from({ length: 7 }, (_, i) => {
const searchQuery = ref('') const variation = Math.sin(seed + i * 0.5) * 20 + Math.cos(seed * 0.3 + i) * 10
return Math.round(basePrice + variation)
// Search with map checkbox
const searchWithMap = ref(false)
const currentBounds = ref<MapBounds | null>(null)
// Map items with correct coordinate field names
const itemsWithCoords = computed(() =>
items.value.filter(item =>
item.locationLatitude != null &&
item.locationLongitude != null &&
!isNaN(Number(item.locationLatitude)) &&
!isNaN(Number(item.locationLongitude))
).map(item => ({
uuid: item.uuid,
name: item.productName || '',
latitude: Number(item.locationLatitude),
longitude: Number(item.locationLongitude)
}))
)
// Filtered items when searchWithMap is enabled
const displayItems = computed(() => {
if (!searchWithMap.value || !currentBounds.value) return items.value
return items.value.filter(item => {
if (item.locationLatitude == null || item.locationLongitude == null) return false
const { west, east, north, south } = currentBounds.value!
const lng = Number(item.locationLongitude)
const lat = Number(item.locationLatitude)
return lng >= west && lng <= east && lat >= south && lat <= north
}) })
})
// Product filter options
const productFilters = computed(() => {
const all = [{ id: 'all', label: t('catalogOffersSection.filters.all_products') }]
const productOptions = products.value.map(p => ({
id: p.uuid,
label: p.name
}))
return [...all, ...productOptions]
})
// Active filter badges
const activeFilterBadges = computed(() => {
const badges: { id: string; label: string }[] = []
if (selectedProductUuid.value) {
const product = products.value.find(p => p.uuid === selectedProductUuid.value)
if (product) badges.push({ id: `product:${product.uuid}`, label: product.name })
}
return badges
})
// Remove filter badge
const onRemoveFilter = (id: string) => {
if (id.startsWith('product:')) {
setProductUuid(null)
}
}
// Handle product filter change
const onProductFilterChange = (value: string) => {
setProductUuid(value === 'all' ? null : value)
}
// Search handler (for future use)
const onSearch = () => {
// TODO: Implement search
}
const onSelectOffer = (offer: any) => {
selectedOfferId.value = offer.uuid
} }
// Initialize // Initialize
await Promise.all([initProducts(), initOffers()]) await init()
useHead(() => ({ useHead(() => ({
title: t('catalogOffersSection.header.title') title: t('catalogProducts.header.title')
})) }))
</script> </script>

View File

@@ -1,255 +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('catalogSupplier.states.loading') }}</Text>
</Stack>
</Section>
<!-- Error / Not Found -->
<Section v-else-if="!supplier" variant="plain" paddingY="lg">
<Card padding="lg">
<Stack align="center" gap="4">
<IconCircle tone="primary">
<Icon name="lucide:building-2" size="24" />
</IconCircle>
<Heading :level="2">{{ t('catalogSupplier.not_found.title') }}</Heading>
<Text tone="muted">{{ t('catalogSupplier.not_found.subtitle') }}</Text>
<Button @click="navigateTo(localePath('/catalog'))">
{{ t('catalogSupplier.actions.back_to_catalog') }}
</Button>
</Stack>
</Card>
</Section>
<template v-else>
<!-- Map Hero -->
<MapHero
:title="supplier.name"
:location="supplierLocation"
:badges="supplierBadges"
:initial-zoom="3"
/>
<!-- Offers Section -->
<Section v-if="offers.length > 0" variant="plain" paddingY="md">
<Stack gap="4">
<Heading :level="2">{{ t('catalogSupplier.sections.offers.title') }}</Heading>
<Grid :cols="1" :md="2" :lg="3" :gap="4">
<OfferCard
v-for="offer in offers"
:key="offer.uuid"
:offer="offer"
/>
</Grid>
</Stack>
</Section>
<!-- Products Section -->
<Section v-if="uniqueProducts.length > 0" variant="plain" paddingY="md">
<Stack gap="4">
<Heading :level="2">{{ t('catalogSupplier.sections.products.title') }}</Heading>
<Stack direction="row" gap="2" wrap>
<NuxtLink
v-for="product in uniqueProducts"
:key="product.uuid"
:to="localePath(`/catalog/products/${product.uuid}`)"
>
<Pill variant="primary" class="hover:bg-primary hover:text-white transition-colors cursor-pointer">
{{ product.name }}
</Pill>
</NuxtLink>
</Stack>
</Stack>
</Section>
<!-- Locations Map Section -->
<Section v-if="uniqueLocations.length > 0" variant="plain" paddingY="md">
<Stack gap="4">
<Heading :level="2">{{ t('catalogSupplier.sections.locations.title') }}</Heading>
<div class="h-64 rounded-lg overflow-hidden border border-base-300 bg-base-100">
<ClientOnly>
<MapboxGlobe
:key="`supplier-locations-${supplierId}`"
:map-id="`supplier-locations-${supplierId}`"
:locations="mapLocations"
:height="256"
:initial-zoom="3"
/>
</ClientOnly>
</div>
<Stack direction="row" gap="2" wrap>
<NuxtLink
v-for="location in uniqueLocations"
:key="location.uuid"
:to="localePath(`/catalog/hubs/${location.uuid}`)"
>
<Pill variant="outline" class="hover:bg-base-200 transition-colors cursor-pointer">
<Icon name="lucide:map-pin" size="14" />
{{ location.name }}
</Pill>
</NuxtLink>
</Stack>
</Stack>
</Section>
</template>
</Stack>
</template>
<script setup lang="ts">
import {
GetSupplierProfileDocument,
GetSupplierOffersDocument,
GetSupplierProfilesDocument,
GetOffersDocument,
} from '~/composables/graphql/public/exchange-generated'
definePageMeta({
layout: 'topnav'
})
const route = useRoute()
const localePath = useLocalePath()
const { t } = useI18n()
const isLoading = ref(true)
const supplier = ref<any>(null)
const offers = ref<any[]>([])
const supplierId = computed(() => route.params.id as string)
// Supplier location for map - use supplier's own coordinates
const supplierLocation = computed(() => {
if (supplier.value?.latitude && supplier.value?.longitude) {
return {
uuid: supplier.value.uuid,
name: supplier.value.name,
latitude: supplier.value.latitude,
longitude: supplier.value.longitude,
country: supplier.value.country,
countryCode: supplier.value.countryCode
}
}
// Fallback to first offer location if supplier has no coordinates
const firstOffer = offers.value.find(o => o.locationLatitude && o.locationLongitude)
if (firstOffer) {
return {
uuid: firstOffer.locationUuid,
name: firstOffer.locationName,
latitude: firstOffer.locationLatitude,
longitude: firstOffer.locationLongitude,
country: firstOffer.locationCountry,
countryCode: firstOffer.locationCountryCode
}
}
return null
})
// Badges for MapHero
const supplierBadges = computed(() => {
const badges: Array<{ icon?: string; text: string }> = []
if (supplier.value?.country) {
badges.push({ icon: 'lucide:globe', text: supplier.value.country })
}
if (supplier.value?.isVerified) {
badges.push({ icon: 'lucide:check-circle', text: t('catalogSupplier.badges.verified') })
}
if (offers.value.length > 0) {
badges.push({ icon: 'lucide:package', text: t('catalogSupplier.badges.offers', { count: offers.value.length }) })
}
return badges
})
// Unique products from offers
const uniqueProducts = computed(() => {
const products = new Map<string, { uuid: string; name: string }>()
offers.value.forEach(offer => {
offer.lines?.forEach((line: any) => {
if (line?.productUuid && line?.productName) {
products.set(line.productUuid, { uuid: line.productUuid, name: line.productName })
}
})
})
return Array.from(products.values())
})
// Unique locations from offers
const uniqueLocations = computed(() => {
const locations = new Map<string, { uuid: string; name: string; latitude: number; longitude: number; country?: string | null; countryCode?: string | null }>()
offers.value.forEach(offer => {
if (offer.locationUuid && offer.locationName && offer.locationLatitude && offer.locationLongitude) {
locations.set(offer.locationUuid, {
uuid: offer.locationUuid,
name: offer.locationName,
latitude: offer.locationLatitude,
longitude: offer.locationLongitude,
country: offer.locationCountry,
countryCode: offer.locationCountryCode
})
}
})
return Array.from(locations.values())
})
// Locations for the map
const mapLocations = computed(() => {
return uniqueLocations.value.map(loc => ({
uuid: loc.uuid,
name: loc.name,
latitude: loc.latitude,
longitude: loc.longitude,
country: ''
}))
})
try {
const { data: supplierData } = await useServerQuery('catalog-supplier-detail', GetSupplierProfileDocument, { uuid: supplierId.value }, 'public', 'exchange')
supplier.value = supplierData.value?.getSupplierProfile || null
if (!supplier.value) {
const { data: suppliersList } = await useServerQuery('catalog-suppliers-fallback', GetSupplierProfilesDocument, {}, 'public', 'exchange')
supplier.value = (suppliersList.value?.getSupplierProfiles || []).find((s: any) => s?.teamUuid === supplierId.value || s?.uuid === supplierId.value) || null
}
const teamIds = [
supplier.value?.teamUuid,
supplier.value?.uuid,
supplierId.value
].filter(Boolean)
if (teamIds.length) {
const primaryId = teamIds[0] as string
const { data: offersData } = await useServerQuery('catalog-supplier-offers', GetSupplierOffersDocument, { teamUuid: primaryId }, 'public', 'exchange')
offers.value = offersData.value?.getOffers || []
if (!offers.value.length) {
const { data: allOffersData } = await useServerQuery('catalog-supplier-offers-fallback', GetOffersDocument, {}, 'public', 'exchange')
const ids = new Set(teamIds)
offers.value = (allOffersData.value?.getOffers || []).filter((o: any) => o?.teamUuid && ids.has(o.teamUuid))
}
}
} catch (error) {
console.error('Error loading supplier:', error)
} finally {
isLoading.value = false
}
// SEO
useHead(() => ({
title: supplier.value?.name
? t('catalogSupplier.meta.title_with_name', { name: supplier.value.name })
: t('catalogSupplier.meta.title'),
meta: [
{
name: 'description',
content: supplier.value?.description
|| (supplier.value?.name
? t('catalogSupplier.meta.description_with_name', { name: supplier.value.name })
: t('catalogSupplier.meta.description'))
}
]
}))
</script>

View File

@@ -0,0 +1,367 @@
<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('catalogSupplierCalculation.states.loading') }}</Text>
</Stack>
</Section>
<!-- Not Found -->
<Section v-else-if="!supplier || !product || !hub" 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('catalogSupplierCalculation.not_found.title') }}</Heading>
<Text tone="muted">{{ t('catalogSupplierCalculation.not_found.subtitle') }}</Text>
<Button @click="navigateTo(localePath(`/catalog/suppliers/${supplierId}/${productId}`))">
{{ t('catalogSupplierCalculation.actions.back_to_hubs') }}
</Button>
</Stack>
</Card>
</Section>
<!-- Content -->
<Section v-else variant="plain" paddingY="lg">
<Stack gap="4">
<!-- Breadcrumbs -->
<SuppliersBreadcrumbs
:supplier-id="supplierId"
:supplier-name="supplier.name"
:product-id="productId"
:product-name="product.name"
:hub-id="hubId"
:hub-name="hub.name"
/>
<!-- Header -->
<div>
<Heading :level="1">{{ product.name }}</Heading>
<div class="flex flex-col gap-1 mt-1">
<Text tone="muted" size="sm">
{{ t('catalogSupplierCalculation.header.supplier') }}: {{ supplier.name }}
</Text>
<Text tone="muted" size="sm">
{{ t('catalogSupplierCalculation.header.from') }}: {{ sourceLocation?.name || t('common.values.not_available') }}
</Text>
<Text tone="muted" size="sm">
{{ t('catalogSupplierCalculation.header.to') }}: {{ hub.name }}, {{ hub.country }}
</Text>
</div>
</div>
<!-- Price chart -->
<Card padding="md">
<Stack gap="2">
<Text weight="semibold" size="sm">{{ t('catalogSupplierCalculation.chart.title') }}</Text>
<div class="h-48">
<ClientOnly>
<apexchart
type="area"
height="180"
:options="chartOptions"
:series="chartSeries"
/>
</ClientOnly>
</div>
</Stack>
</Card>
<!-- Route Loading -->
<Section v-if="isLoadingRoute" variant="plain">
<Stack align="center" gap="2">
<Spinner />
<Text tone="muted">{{ t('catalogSupplierCalculation.states.calculating_route') }}</Text>
</Stack>
</Section>
<!-- Route Result -->
<template v-else-if="route">
<Card padding="md">
<Stack gap="3">
<div class="flex justify-between items-center">
<Text weight="semibold">{{ t('catalogSupplierCalculation.route.title') }}</Text>
<div class="flex gap-2">
<span class="badge badge-primary">{{ formatDistance(route.totalDistanceKm) }}</span>
<span class="badge badge-neutral">{{ formatDuration(route.totalTimeSeconds) }}</span>
</div>
</div>
<!-- Route stages -->
<div class="space-y-2">
<div
v-for="(stage, index) in route.stages"
:key="index"
class="flex items-center gap-3 p-2 bg-base-200 rounded-lg"
>
<div class="w-8 h-8 flex items-center justify-center bg-base-100 rounded-full">
<Icon :name="getTransportIcon(stage.transportType)" size="16" />
</div>
<div class="flex-1">
<Text size="sm" weight="medium">{{ stage.fromName }} {{ stage.toName }}</Text>
<Text size="xs" tone="muted">
{{ formatDistance(stage.distanceKm) }} · {{ formatDuration(stage.travelTimeSeconds) }}
</Text>
</div>
<span class="badge badge-sm badge-outline">{{ stage.transportType }}</span>
</div>
</div>
</Stack>
</Card>
</template>
<!-- No Route -->
<Card v-else padding="md">
<Stack align="center" gap="2">
<Icon name="lucide:route-off" size="32" class="text-base-content/40" />
<Text tone="muted">{{ t('catalogSupplierCalculation.route.not_found') }}</Text>
</Stack>
</Card>
</Stack>
</Section>
</Stack>
</template>
<script setup lang="ts">
import { GetNodeConnectionsDocument, FindRoutesDocument } from '~/composables/graphql/public/geo-generated'
import {
GetSupplierProfileDocument,
GetSupplierOffersDocument,
GetSupplierProfilesDocument,
GetOffersDocument,
} 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 isLoadingRoute = ref(false)
const supplier = ref<any>(null)
const product = ref<{ uuid: string; name: string } | null>(null)
const hub = ref<any>(null)
const sourceLocation = ref<{ uuid: string; name: string } | null>(null)
const routeData = ref<any>(null)
const supplierId = computed(() => route.params.supplierId as string)
const productId = computed(() => route.params.productId as string)
const hubId = computed(() => route.params.hubId as string)
// Format distance
const formatDistance = (km?: number | null) => {
if (!km) return t('common.values.not_available')
return `${Math.round(km)} km`
}
// Format duration
const formatDuration = (seconds?: number | null) => {
if (!seconds) return t('common.values.not_available')
const hours = Math.floor(seconds / 3600)
const days = Math.floor(hours / 24)
if (days > 0) return `${days}d ${hours % 24}h`
return `${hours}h`
}
// Get transport icon
const getTransportIcon = (type?: string | null) => {
switch (type?.toLowerCase()) {
case 'auto':
case 'road':
return 'lucide:truck'
case 'rail':
case 'train':
return 'lucide:train'
case 'sea':
case 'ship':
return 'lucide:ship'
case 'air':
case 'plane':
return 'lucide:plane'
default:
return 'lucide:route'
}
}
// Mock price history generator
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)
})
}
const priceHistory = computed(() => product.value ? getMockPriceHistory(product.value.uuid) : [])
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('catalogSupplierCalculation.chart.price'),
data: priceHistory.value
}])
// Load route using FindRoutes (single source!)
const loadRoute = async () => {
if (!sourceLocation.value || !hubId.value) {
routeData.value = null
return
}
isLoadingRoute.value = true
try {
const data = await execute(
FindRoutesDocument,
{
fromUuid: sourceLocation.value.uuid,
toUuid: hubId.value,
limit: 1
},
'public',
'geo'
)
routeData.value = data?.findRoutes?.[0] || null
} catch (error) {
console.error('Error loading route:', error)
routeData.value = null
} finally {
isLoadingRoute.value = false
}
}
// Load data
try {
// Get hub info
const { data: hubData } = await useServerQuery(
'hub-info',
GetNodeConnectionsDocument,
{ uuid: hubId.value },
'public',
'geo'
)
hub.value = hubData.value?.nodeConnections?.hub || null
// Get supplier
const { data: supplierData } = await useServerQuery(
'supplier-profile',
GetSupplierProfileDocument,
{ uuid: supplierId.value },
'public',
'exchange'
)
supplier.value = supplierData.value?.getSupplierProfile || null
if (!supplier.value) {
const { data: suppliersList } = await useServerQuery(
'suppliers-fallback',
GetSupplierProfilesDocument,
{},
'public',
'exchange'
)
supplier.value = (suppliersList.value?.getSupplierProfiles || [])
.find((s: any) => s?.teamUuid === supplierId.value || s?.uuid === supplierId.value) || null
}
// Get supplier's offers to find product and source location
if (supplier.value) {
const teamIds = [supplier.value?.teamUuid, supplier.value?.uuid, supplierId.value].filter(Boolean)
const primaryId = teamIds[0] as string
const { data: offersData } = await useServerQuery(
'supplier-offers',
GetSupplierOffersDocument,
{ teamUuid: primaryId },
'public',
'exchange'
)
let offers = offersData.value?.getOffers || []
if (!offers.length) {
const { data: allOffersData } = await useServerQuery(
'supplier-offers-fallback',
GetOffersDocument,
{},
'public',
'exchange'
)
const ids = new Set(teamIds)
offers = (allOffersData.value?.getOffers || []).filter((o: any) => o?.teamUuid && ids.has(o.teamUuid))
}
// Find product and source location in offers
for (const offer of offers) {
const line = offer.lines?.find((l: any) => l?.productUuid === productId.value)
if (line) {
product.value = { uuid: line.productUuid, name: line.productName }
if (offer.locationUuid && offer.locationName) {
sourceLocation.value = { uuid: offer.locationUuid, name: offer.locationName }
}
break
}
}
}
// Load route after getting source location
if (sourceLocation.value && hub.value) {
await loadRoute()
}
} 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('catalogSupplierCalculation.meta.title'),
meta: [
{
name: 'description',
content: t('catalogSupplierCalculation.meta.description', {
product: product.value?.name || '',
supplier: supplier.value?.name || '',
hub: hub.value?.name || ''
})
}
]
}))
</script>

View File

@@ -0,0 +1,244 @@
<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('catalogSupplierProductHubs.states.loading') }}</Text>
</Stack>
</Section>
<!-- Not Found -->
<Section v-else-if="!supplier || !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('catalogSupplierProductHubs.not_found.title') }}</Heading>
<Text tone="muted">{{ t('catalogSupplierProductHubs.not_found.subtitle') }}</Text>
<Button @click="navigateTo(localePath(`/catalog/suppliers/${supplierId}`))">
{{ t('catalogSupplierProductHubs.actions.back_to_supplier') }}
</Button>
</Stack>
</Card>
</Section>
<!-- Content -->
<Section v-else variant="plain" paddingY="lg">
<Stack gap="4">
<!-- Breadcrumbs -->
<SuppliersBreadcrumbs
:supplier-id="supplierId"
:supplier-name="supplier.name"
:product-id="productId"
:product-name="product.name"
/>
<!-- Header -->
<div>
<Heading :level="1">{{ product.name }}</Heading>
<Text tone="muted" size="sm">
{{ t('catalogSupplierProductHubs.header.from_supplier', { supplier: supplier.name }) }}
</Text>
<Text tone="muted" size="sm" v-if="sourceLocation">
{{ t('catalogSupplierProductHubs.header.source_location', { location: sourceLocation.name }) }}
</Text>
</div>
<!-- Price chart -->
<Card padding="md">
<div class="h-48">
<ClientOnly>
<apexchart
type="area"
height="180"
:options="chartOptions"
:series="chartSeries"
/>
</ClientOnly>
</div>
</Card>
<!-- Hubs Section -->
<div>
<Text weight="semibold" size="lg" class="mb-3">
{{ t('catalogSupplierProductHubs.header.hubs_title', { count: hubs.length }) }}
</Text>
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
<HubCard
v-for="hub in hubs"
:key="hub.uuid"
:hub="hub"
:link-to="localePath(`/catalog/suppliers/${supplierId}/${productId}/${hub.uuid}`)"
/>
</div>
</div>
<!-- Empty state -->
<Stack v-if="hubs.length === 0" align="center" gap="2">
<Icon name="lucide:map-pin-off" size="32" class="text-base-content/40" />
<Text tone="muted">{{ t('catalogSupplierProductHubs.empty.no_hubs') }}</Text>
</Stack>
</Stack>
</Section>
</Stack>
</template>
<script setup lang="ts">
import { GetNodesDocument } from '~/composables/graphql/public/geo-generated'
import {
GetSupplierProfileDocument,
GetSupplierOffersDocument,
GetSupplierProfilesDocument,
GetOffersDocument,
} from '~/composables/graphql/public/exchange-generated'
definePageMeta({
layout: 'topnav'
})
const route = useRoute()
const localePath = useLocalePath()
const { t } = useI18n()
const isLoading = ref(true)
const supplier = ref<any>(null)
const product = ref<{ uuid: string; name: string } | null>(null)
const sourceLocation = ref<{ uuid: string; name: string } | null>(null)
const hubs = ref<Array<{ uuid: string; name: string; country?: string; countryCode?: string }>>([])
const supplierId = computed(() => route.params.supplierId as string)
const productId = computed(() => route.params.productId as string)
// Mock price history generator
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) * 20 + Math.cos(seed * 0.2 + i) * 15
return Math.round(basePrice + variation)
})
}
const priceHistory = computed(() => product.value ? getMockPriceHistory(product.value.uuid) : [])
// Chart configuration
const chartOptions = computed(() => ({
chart: {
type: 'area',
sparkline: { enabled: false },
toolbar: { show: false },
animations: { enabled: false }
},
stroke: { curve: 'smooth', width: 2 },
fill: {
type: 'gradient',
gradient: { shadeIntensity: 1, opacityFrom: 0.4, opacityTo: 0.1 }
},
colors: ['#3b82f6'],
xaxis: {
labels: { show: false },
axisBorder: { show: false },
axisTicks: { show: false }
},
yaxis: { labels: { show: true } },
grid: { show: true, borderColor: '#e5e7eb', strokeDashArray: 4 },
tooltip: { enabled: true }
}))
const chartSeries = computed(() => [{
name: t('catalogSupplierProductHubs.chart.price'),
data: priceHistory.value
}])
// Load data
try {
// Get supplier
const { data: supplierData } = await useServerQuery(
'supplier-profile',
GetSupplierProfileDocument,
{ uuid: supplierId.value },
'public',
'exchange'
)
supplier.value = supplierData.value?.getSupplierProfile || null
if (!supplier.value) {
const { data: suppliersList } = await useServerQuery(
'suppliers-fallback',
GetSupplierProfilesDocument,
{},
'public',
'exchange'
)
supplier.value = (suppliersList.value?.getSupplierProfiles || [])
.find((s: any) => s?.teamUuid === supplierId.value || s?.uuid === supplierId.value) || null
}
// Get supplier's offers to find product and location
if (supplier.value) {
const teamIds = [supplier.value?.teamUuid, supplier.value?.uuid, supplierId.value].filter(Boolean)
const primaryId = teamIds[0] as string
const { data: offersData } = await useServerQuery(
'supplier-offers',
GetSupplierOffersDocument,
{ teamUuid: primaryId },
'public',
'exchange'
)
let offers = offersData.value?.getOffers || []
if (!offers.length) {
const { data: allOffersData } = await useServerQuery(
'supplier-offers-fallback',
GetOffersDocument,
{},
'public',
'exchange'
)
const ids = new Set(teamIds)
offers = (allOffersData.value?.getOffers || []).filter((o: any) => o?.teamUuid && ids.has(o.teamUuid))
}
// Find product in offers
for (const offer of offers) {
const line = offer.lines?.find((l: any) => l?.productUuid === productId.value)
if (line) {
product.value = { uuid: line.productUuid, name: line.productName }
if (offer.locationUuid && offer.locationName) {
sourceLocation.value = { uuid: offer.locationUuid, name: offer.locationName }
}
break
}
}
}
// Get hubs (destinations)
const { data: hubsData } = await useServerQuery(
'all-hubs',
GetNodesDocument,
{ limit: 100 },
'public',
'geo'
)
hubs.value = (hubsData.value?.nodes || [])
.filter((h): h is { uuid: string; name: string; country?: string; countryCode?: string } =>
h !== null && !!h.uuid && !!h.name
)
.map(h => ({ uuid: h.uuid!, name: h.name!, country: h.country || undefined, countryCode: h.countryCode || undefined }))
} catch (error) {
console.error('Error loading data:', error)
} finally {
isLoading.value = false
}
// SEO
useHead(() => ({
title: product.value?.name && supplier.value?.name
? `${product.value.name} - ${supplier.value.name}`
: t('catalogSupplierProductHubs.meta.title')
}))
</script>

View File

@@ -0,0 +1,202 @@
<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('catalogSupplierProducts.states.loading') }}</Text>
</Stack>
</Section>
<!-- Supplier Not Found -->
<Section v-else-if="!supplier" variant="plain" paddingY="lg">
<Card padding="lg">
<Stack align="center" gap="4">
<IconCircle tone="primary">
<Icon name="lucide:building-2" size="24" />
</IconCircle>
<Heading :level="2">{{ t('catalogSupplierProducts.not_found.title') }}</Heading>
<Text tone="muted">{{ t('catalogSupplierProducts.not_found.subtitle') }}</Text>
<Button @click="navigateTo(localePath('/catalog/suppliers'))">
{{ t('catalogSupplierProducts.actions.back_to_suppliers') }}
</Button>
</Stack>
</Card>
</Section>
<!-- Content -->
<Section v-else variant="plain" paddingY="lg">
<Stack gap="4">
<!-- Breadcrumbs -->
<SuppliersBreadcrumbs :supplier-id="supplierId" :supplier-name="supplier.name" />
<!-- Header with supplier info -->
<div class="flex items-start gap-4">
<!-- Logo -->
<div v-if="supplier.logo" class="w-16 h-16 shrink-0">
<img :src="supplier.logo" :alt="supplier.name || ''" class="w-full h-full object-contain rounded-lg">
</div>
<div v-else class="w-16 h-16 bg-primary/10 text-primary font-bold rounded-lg flex items-center justify-center text-2xl shrink-0">
{{ supplier.name?.charAt(0) }}
</div>
<div>
<Heading :level="1">{{ supplier.name }}</Heading>
<Text tone="muted" size="sm">{{ supplier.country }}</Text>
<div class="flex gap-2 mt-1">
<span v-if="supplier.isVerified" class="badge badge-success badge-sm">
{{ t('catalogSupplier.badges.verified') }}
</span>
</div>
</div>
</div>
<!-- Products Section -->
<div>
<Text weight="semibold" size="lg" class="mb-3">{{ t('catalogSupplierProducts.header.products_title', { count: products.length }) }}</Text>
<div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
<HubProductCard
v-for="product in products"
:key="product.uuid"
:name="product.name"
:price-history="getMockPriceHistory(product.uuid)"
@select="goToProduct(product.uuid)"
/>
</div>
</div>
<!-- Empty state -->
<Stack v-if="products.length === 0" align="center" gap="2">
<Icon name="lucide:package-x" size="32" class="text-base-content/40" />
<Text tone="muted">{{ t('catalogSupplierProducts.empty.no_products') }}</Text>
</Stack>
</Stack>
</Section>
</Stack>
</template>
<script setup lang="ts">
import {
GetSupplierProfileDocument,
GetSupplierOffersDocument,
GetSupplierProfilesDocument,
GetOffersDocument,
} from '~/composables/graphql/public/exchange-generated'
definePageMeta({
layout: 'topnav'
})
const route = useRoute()
const localePath = useLocalePath()
const { t } = useI18n()
const isLoading = ref(true)
const supplier = ref<any>(null)
const offers = ref<any[]>([])
const supplierId = computed(() => route.params.supplierId as string)
// Extract unique products from offers
const products = computed(() => {
const productsMap = new Map<string, { uuid: string; name: string; locationUuid?: string }>()
offers.value.forEach(offer => {
offer.lines?.forEach((line: any) => {
if (line?.productUuid && line?.productName && !productsMap.has(line.productUuid)) {
productsMap.set(line.productUuid, {
uuid: line.productUuid,
name: line.productName,
locationUuid: offer.locationUuid
})
}
})
})
return Array.from(productsMap.values())
})
// Navigate to product detail
const goToProduct = (productId: string) => {
navigateTo(localePath(`/catalog/suppliers/${supplierId.value}/${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)
})
}
// Load data
try {
// Try to get supplier by UUID first
const { data: supplierData } = await useServerQuery(
'supplier-profile',
GetSupplierProfileDocument,
{ uuid: supplierId.value },
'public',
'exchange'
)
supplier.value = supplierData.value?.getSupplierProfile || null
// Fallback to searching in all suppliers
if (!supplier.value) {
const { data: suppliersList } = await useServerQuery(
'suppliers-fallback',
GetSupplierProfilesDocument,
{},
'public',
'exchange'
)
supplier.value = (suppliersList.value?.getSupplierProfiles || [])
.find((s: any) => s?.teamUuid === supplierId.value || s?.uuid === supplierId.value) || null
}
// Get supplier's offers
if (supplier.value) {
const teamIds = [
supplier.value?.teamUuid,
supplier.value?.uuid,
supplierId.value
].filter(Boolean)
if (teamIds.length) {
const primaryId = teamIds[0] as string
const { data: offersData } = await useServerQuery(
'supplier-offers',
GetSupplierOffersDocument,
{ teamUuid: primaryId },
'public',
'exchange'
)
offers.value = offersData.value?.getOffers || []
// Fallback if no offers found
if (!offers.value.length) {
const { data: allOffersData } = await useServerQuery(
'supplier-offers-fallback',
GetOffersDocument,
{},
'public',
'exchange'
)
const ids = new Set(teamIds)
offers.value = (allOffersData.value?.getOffers || [])
.filter((o: any) => o?.teamUuid && ids.has(o.teamUuid))
}
}
}
} catch (error) {
console.error('Error loading supplier products:', error)
} finally {
isLoading.value = false
}
// SEO
useHead(() => ({
title: supplier.value?.name
? t('catalogSupplierProducts.meta.title_with_name', { name: supplier.value.name })
: t('catalogSupplierProducts.meta.title')
}))
</script>