@shopbite-de/storefront 1.21.1 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,55 @@
1
+ <script setup lang="ts">
2
+ import type { Schemas } from "#shopware";
3
+
4
+ defineProps<{
5
+ filter: Schemas["PropertyGroup"];
6
+ modelValue: string[];
7
+ }>();
8
+
9
+ defineEmits<{
10
+ "update:modelValue": [value: string[]];
11
+ }>();
12
+ </script>
13
+
14
+ <template>
15
+ <UCollapsible class="flex flex-col gap-2 w-48" :default-open="true">
16
+ <UButton
17
+ :label="filter.translated.name"
18
+ color="neutral"
19
+ variant="subtle"
20
+ trailing-icon="i-lucide-chevron-down"
21
+ block
22
+ :ui="{
23
+ trailingIcon:
24
+ 'group-data-[state=open]:rotate-180 transition-transform duration-200',
25
+ }"
26
+ />
27
+
28
+ <template #content>
29
+ <UCheckboxGroup
30
+ :model-value="modelValue"
31
+ :items="filter.options"
32
+ value-key="id"
33
+ label-key="translated.name"
34
+ @update:model-value="$emit('update:modelValue', $event)"
35
+ >
36
+ <template
37
+ v-if="
38
+ (filter.displayType ?? filter.translated.displayType) === 'media'
39
+ "
40
+ #label="{ item }"
41
+ >
42
+ <div class="flex items-center gap-1.5">
43
+ <NuxtImg
44
+ v-if="item.media?.url"
45
+ :src="item.media.url"
46
+ :alt="item.translated.name"
47
+ class="h-4 w-4 object-contain"
48
+ />
49
+ <span>{{ item.translated.name }}</span>
50
+ </div>
51
+ </template>
52
+ </UCheckboxGroup>
53
+ </template>
54
+ </UCollapsible>
55
+ </template>
@@ -10,6 +10,11 @@ const { id: categoryId } = toRefs(props);
10
10
 
11
11
  const { category } = await useCategory(categoryId);
12
12
 
13
+ const selectedPropertyFilters = useState<string[]>(
14
+ "listing-property-filters",
15
+ () => [],
16
+ );
17
+
13
18
  const {
14
19
  showSkeleton,
15
20
  loading,
@@ -20,8 +25,13 @@ const {
20
25
  currentFilters,
21
26
  changeSorting,
22
27
  setFilters,
23
- resetFilters,
24
- } = useCategoryListing(props.id);
28
+ resetFilters: resetListingFilters,
29
+ } = useCategoryListing(props.id, selectedPropertyFilters.value);
30
+
31
+ async function resetFilters() {
32
+ selectedPropertyFilters.value = [];
33
+ await resetListingFilters();
34
+ }
25
35
 
26
36
  useCategorySeo(category);
27
37
 
@@ -43,8 +53,6 @@ const propertyFilters = computed<Schemas["PropertyGroup"][]>(
43
53
  (availableFilter) => availableFilter.code === "properties",
44
54
  ) ?? []) as unknown as Schemas["PropertyGroup"][],
45
55
  );
46
-
47
- const selectedPropertyFilters = ref(currentFilters.value?.properties ?? []);
48
56
  const selectedPropertyFiltersString = computed(() =>
49
57
  selectedPropertyFilters.value?.join("|"),
50
58
  );
@@ -58,6 +66,27 @@ const selectedListingFilters = computed<ShortcutFilterParam[]>(() => {
58
66
  ];
59
67
  });
60
68
 
69
+ // When the listing loads for a new category, drop any persisted filters whose
70
+ // option IDs don't exist in this category's available options.
71
+ watch(
72
+ propertyFilters,
73
+ (filters) => {
74
+ if (selectedPropertyFilters.value.length === 0) return;
75
+
76
+ const availableOptionIds = new Set(
77
+ filters.flatMap((f) => f.options?.map((o) => o.id) ?? []),
78
+ );
79
+ const valid = selectedPropertyFilters.value.filter((id) =>
80
+ availableOptionIds.has(id),
81
+ );
82
+
83
+ if (valid.length !== selectedPropertyFilters.value.length) {
84
+ selectedPropertyFilters.value = valid;
85
+ }
86
+ },
87
+ { once: true },
88
+ );
89
+
61
90
  let filterChain = Promise.resolve();
62
91
 
63
92
  watch(selectedListingFilters, (newFilters, oldFilters) => {
@@ -96,6 +125,7 @@ const moreThanOneFilterAndOption = computed<boolean>(
96
125
  <div>
97
126
  <Breadcrumb :category-id="category?.id" />
98
127
  <CategoryHeader v-if="category" :category="category" />
128
+ <CategorySearchInput class="mb-4 grow flex" />
99
129
  <div class="flex flex-row justify-between gap-4 mb-4">
100
130
  <UBadge variant="subtle" :label="`${elements.length} Produkte`" />
101
131
  <USelect
@@ -116,37 +146,12 @@ const moreThanOneFilterAndOption = computed<boolean>(
116
146
 
117
147
  <template #body>
118
148
  <div class="flex flex-col gap-4">
119
- <div
149
+ <CategoryFilterGroup
120
150
  v-for="filter in propertyFilters"
121
151
  :key="filter.id"
122
- class="flex flex-col gap-4"
123
- >
124
- <UCollapsible
125
- class="flex flex-col gap-2 w-48"
126
- :default-open="true"
127
- >
128
- <UButton
129
- :label="filter.translated.name"
130
- color="neutral"
131
- variant="subtle"
132
- trailing-icon="i-lucide-chevron-down"
133
- block
134
- :ui="{
135
- trailingIcon:
136
- 'group-data-[state=open]:rotate-180 transition-transform duration-200',
137
- }"
138
- />
139
-
140
- <template #content>
141
- <UCheckboxGroup
142
- v-model="selectedPropertyFilters"
143
- :items="filter.options"
144
- value-key="id"
145
- label-key="translated.name"
146
- />
147
- </template>
148
- </UCollapsible>
149
- </div>
152
+ v-model="selectedPropertyFilters"
153
+ :filter="filter"
154
+ />
150
155
  <UButton
151
156
  label="Zurücksetzen"
152
157
  variant="outline"
@@ -192,37 +197,12 @@ const moreThanOneFilterAndOption = computed<boolean>(
192
197
  <ClientOnly v-if="moreThanOneFilterAndOption">
193
198
  <div class="flex flex-col gap-4">
194
199
  <h2 class="text-3xl md:text-4xl mb-3 pb-2">Filter</h2>
195
- <div
200
+ <CategoryFilterGroup
196
201
  v-for="filter in propertyFilters"
197
202
  :key="filter.id"
198
- class="flex flex-col gap-4"
199
- >
200
- <UCollapsible
201
- class="flex flex-col gap-2 w-48"
202
- :default-open="true"
203
- >
204
- <UButton
205
- :label="filter.translated.name"
206
- color="neutral"
207
- variant="subtle"
208
- trailing-icon="i-lucide-chevron-down"
209
- block
210
- :ui="{
211
- trailingIcon:
212
- 'group-data-[state=open]:rotate-180 transition-transform duration-200',
213
- }"
214
- />
215
-
216
- <template #content>
217
- <UCheckboxGroup
218
- v-model="selectedPropertyFilters"
219
- :items="filter.options"
220
- value-key="id"
221
- label-key="translated.name"
222
- />
223
- </template>
224
- </UCollapsible>
225
- </div>
203
+ v-model="selectedPropertyFilters"
204
+ :filter="filter"
205
+ />
226
206
  <UButton
227
207
  label="Zurücksetzen"
228
208
  variant="outline"
@@ -0,0 +1,33 @@
1
+ <script setup lang="ts">
2
+ const router = useRouter();
3
+
4
+ const query = ref("");
5
+
6
+ function submit() {
7
+ const term = query.value.trim();
8
+ if (!term) return;
9
+ router.push({ path: "/suche", query: { q: term } });
10
+ }
11
+ </script>
12
+
13
+ <template>
14
+ <UInput
15
+ v-model="query"
16
+ name="search"
17
+ size="md"
18
+ icon="i-lucide-search"
19
+ placeholder="Produkte suchen..."
20
+ @keyup.enter="submit"
21
+ >
22
+ <template v-if="query" #trailing>
23
+ <UButton
24
+ color="neutral"
25
+ variant="link"
26
+ size="sm"
27
+ icon="i-lucide-circle-x"
28
+ aria-label="Suche leeren"
29
+ @click="query = ''"
30
+ />
31
+ </template>
32
+ </UInput>
33
+ </template>
@@ -7,58 +7,18 @@ const props = defineProps<{
7
7
  withAddToCartButton: boolean;
8
8
  }>();
9
9
 
10
- const { isCheckoutEnabled } = useShopBiteConfig();
10
+ const { product } = toRefs(props);
11
11
 
12
- const { product, withFavoriteButton, withAddToCartButton } = toRefs(props);
13
-
14
- const { getFormattedPrice } = usePrice({
15
- currencyCode: "EUR",
16
- localeCode: "de-DE",
17
- });
12
+ const sortedProperties = computed(
13
+ () =>
14
+ product.value.sortedProperties as Schemas["PropertyGroup"][] | undefined,
15
+ );
18
16
 
19
17
  const price = ref(product.value.calculatedPrice.totalPrice);
20
18
  const label = ref(product.value.translated.name ?? product.value.name);
21
19
  const description = ref(product.value.description);
22
20
  const number = ref(product.value.productNumber);
23
21
 
24
- const isVegi = computed<boolean>(() => {
25
- if (!product.value?.properties) {
26
- return false;
27
- }
28
-
29
- return (
30
- (
31
- product.value?.sortedProperties as Schemas["PropertyGroup"][] | undefined
32
- )?.some(
33
- (propertyGroup: Schemas["PropertyGroup"]) =>
34
- propertyGroup.translated.name === "Vegetarisch" &&
35
- propertyGroup.options?.some(
36
- (option: Schemas["PropertyGroupOption"]) =>
37
- option.translated.name === "Ja",
38
- ),
39
- ) ?? false
40
- );
41
- });
42
- const openDetails = ref(false);
43
-
44
- function toggleDetails() {
45
- openDetails.value = !openDetails.value;
46
- }
47
-
48
- const MAIN_INGREDIENTS_PROPERTY_LABEL = "Hauptzutaten";
49
-
50
- const mainIngredients = computed<Schemas["PropertyGroupOption"][]>(() => {
51
- const sortedProps =
52
- (product.value?.sortedProperties as
53
- | Schemas["PropertyGroup"][]
54
- | undefined) ?? ([] as Schemas["PropertyGroup"][]);
55
- const mainIngredientsProperty = sortedProps.find(
56
- (propertyGroup: Schemas["PropertyGroup"]) =>
57
- propertyGroup.translated.name === MAIN_INGREDIENTS_PROPERTY_LABEL,
58
- );
59
- return mainIngredientsProperty?.options ?? [];
60
- });
61
-
62
22
  function onVariantSelected(variant: Schemas["Product"]) {
63
23
  price.value = variant.calculatedPrice.totalPrice;
64
24
  label.value = variant.translated.name ?? variant.name;
@@ -81,28 +41,21 @@ function onVariantSelected(variant: Schemas["Product"]) {
81
41
  :ui="{ footer: 'w-full', root: 'shadow-lg' }"
82
42
  >
83
43
  <template #header>
84
- <LazyUBadge
85
- v-if="isVegi"
86
- icon="i-lucide-leaf"
87
- color="success"
88
- variant="outline"
89
- size="sm"
90
- label="Vegetarisch"
91
- />
44
+ <ProductCardDietBadges :sorted-properties="sortedProperties" />
92
45
  </template>
93
46
 
94
47
  <div v-if="product.cover?.media?.url">
95
48
  <LazyNuxtImg
96
49
  :src="product.cover.media.url"
97
- class="rounded-md h-auto max-w-full object-contain ransition-opacity duration-700"
50
+ class="rounded-md h-auto max-w-full object-contain transition-opacity duration-700"
98
51
  sizes="(min-width: 1024px) 50vw, 100vw"
99
52
  />
100
53
  </div>
101
54
 
102
55
  <template #title>
103
- <div class="flex flex-row items-baseline gap-1">
56
+ <div class="flex flex-row items-center gap-1">
104
57
  <span class="text-sm text-brand-500">#{{ number }}</span>
105
-
58
+ <ProductCardKitchen :sorted-properties="sortedProperties" />
106
59
  <p class="text-base text-pretty font-semibold text-highlighted">
107
60
  {{ label }}
108
61
  </p>
@@ -110,45 +63,20 @@ function onVariantSelected(variant: Schemas["Product"]) {
110
63
  </template>
111
64
 
112
65
  <template #description>
113
- <div class="flex flex-col gap-2">
114
- <div>{{ description }}</div>
115
- <div
116
- v-if="mainIngredients.length > 0"
117
- class="font-extralight text-sm text-pretty"
118
- >
119
- {{
120
- mainIngredients
121
- .map((ingredient) => ingredient.translated.name)
122
- .join(", ")
123
- }}
124
- </div>
125
- </div>
66
+ <ProductCardDescription
67
+ :description="description"
68
+ :sorted-properties="sortedProperties"
69
+ />
126
70
  </template>
127
71
 
128
72
  <template #footer>
129
- <div class="flex flex-row justify-between content-center w-full">
130
- <p>{{ getFormattedPrice(price) }}</p>
131
- <div class="flex flex-row gap-2">
132
- <AddToWishlist v-if="withFavoriteButton" :product="product" />
133
- <UButton
134
- v-if="withAddToCartButton && isCheckoutEnabled"
135
- icon="i-lucide-shopping-cart"
136
- variant="subtle"
137
- @click="toggleDetails"
138
- />
139
- </div>
140
- </div>
141
- <ClientOnly>
142
- <UCollapsible v-model:open="openDetails" class="flex flex-col gap-2">
143
- <template #content>
144
- <LazyProductDetail
145
- :product-id="product.id"
146
- @product-added="toggleDetails"
147
- @variant-selected="onVariantSelected"
148
- />
149
- </template>
150
- </UCollapsible>
151
- </ClientOnly>
73
+ <ProductCardFooter
74
+ :price="price"
75
+ :product="product"
76
+ :with-favorite-button="withFavoriteButton"
77
+ :with-add-to-cart-button="withAddToCartButton"
78
+ @variant-selected="onVariantSelected"
79
+ />
152
80
  </template>
153
81
  </UPageCard>
154
82
  </AnimatedSection>
@@ -0,0 +1,27 @@
1
+ <script setup lang="ts">
2
+ import type { Schemas } from "#shopware";
3
+
4
+ const props = defineProps<{
5
+ description: string | null | undefined;
6
+ sortedProperties: Schemas["PropertyGroup"][] | undefined;
7
+ }>();
8
+
9
+ const mainIngredients = computed<Schemas["PropertyGroupOption"][]>(() => {
10
+ const group = props.sortedProperties?.find(
11
+ (propertyGroup) => propertyGroup.translated.name === "Hauptzutaten",
12
+ );
13
+ return group?.options ?? [];
14
+ });
15
+ </script>
16
+
17
+ <template>
18
+ <div class="flex flex-col gap-2">
19
+ <div>{{ description }}</div>
20
+ <div
21
+ v-if="mainIngredients.length > 0"
22
+ class="font-extralight text-sm text-pretty"
23
+ >
24
+ {{ mainIngredients.map((i) => i.translated.name).join(", ") }}
25
+ </div>
26
+ </div>
27
+ </template>
@@ -0,0 +1,42 @@
1
+ <script setup lang="ts">
2
+ import type { Schemas } from "#shopware";
3
+
4
+ const props = defineProps<{
5
+ sortedProperties: Schemas["PropertyGroup"][] | undefined;
6
+ }>();
7
+
8
+ const isVegi = computed<boolean>(
9
+ () =>
10
+ props.sortedProperties?.some(
11
+ (group) =>
12
+ group.translated.name === "Vegetarisch" &&
13
+ group.options?.some((option) => option.translated.name === "Ja"),
14
+ ) ?? false,
15
+ );
16
+
17
+ const isVegan = computed<boolean>(
18
+ () =>
19
+ props.sortedProperties?.some(
20
+ (group) =>
21
+ group.translated.name === "Vegan" &&
22
+ group.options?.some((option) => option.translated.name === "Ja"),
23
+ ) ?? false,
24
+ );
25
+ </script>
26
+
27
+ <template>
28
+ <LazyUBadge
29
+ v-if="isVegi"
30
+ icon="i-lucide-leaf"
31
+ color="success"
32
+ variant="outline"
33
+ label="Vegetarisch"
34
+ />
35
+ <LazyUBadge
36
+ v-if="isVegan"
37
+ icon="i-lucide-vegan"
38
+ color="success"
39
+ variant="outline"
40
+ label="Vegan"
41
+ />
42
+ </template>
@@ -0,0 +1,54 @@
1
+ <script setup lang="ts">
2
+ import type { Schemas } from "#shopware";
3
+
4
+ defineProps<{
5
+ price: number;
6
+ product: Schemas["Product"];
7
+ withFavoriteButton: boolean;
8
+ withAddToCartButton: boolean;
9
+ }>();
10
+
11
+ const emit = defineEmits<{
12
+ variantSelected: [variant: Schemas["Product"]];
13
+ }>();
14
+
15
+ const { isCheckoutEnabled } = useShopBiteConfig();
16
+
17
+ const { getFormattedPrice } = usePrice({
18
+ currencyCode: "EUR",
19
+ localeCode: "de-DE",
20
+ });
21
+
22
+ const openDetails = ref(false);
23
+
24
+ function toggleDetails() {
25
+ openDetails.value = !openDetails.value;
26
+ }
27
+ </script>
28
+
29
+ <template>
30
+ <div class="flex flex-row justify-between content-center w-full">
31
+ <p>{{ getFormattedPrice(price) }}</p>
32
+ <div class="flex flex-row gap-2">
33
+ <AddToWishlist v-if="withFavoriteButton" :product="product" />
34
+ <UButton
35
+ v-if="withAddToCartButton && isCheckoutEnabled"
36
+ icon="i-lucide-shopping-cart"
37
+ variant="subtle"
38
+ aria-label="Öffnet Produkt-Optionen"
39
+ @click="toggleDetails"
40
+ />
41
+ </div>
42
+ </div>
43
+ <ClientOnly>
44
+ <UCollapsible v-model:open="openDetails" class="flex flex-col gap-2">
45
+ <template #content>
46
+ <LazyProductDetail
47
+ :product-id="product.id"
48
+ @product-added="toggleDetails"
49
+ @variant-selected="emit('variantSelected', $event)"
50
+ />
51
+ </template>
52
+ </UCollapsible>
53
+ </ClientOnly>
54
+ </template>
@@ -0,0 +1,34 @@
1
+ <script setup lang="ts">
2
+ import type { Schemas } from "#shopware";
3
+
4
+ const props = defineProps<{
5
+ sortedProperties: Schemas["PropertyGroup"][] | undefined;
6
+ }>();
7
+
8
+ const kitchen = computed<
9
+ { name: string; mediaUrl?: string; isImage: boolean } | undefined
10
+ >(() => {
11
+ const group = props.sortedProperties?.find(
12
+ (propertyGroup) => propertyGroup.translated.name === "Küche",
13
+ );
14
+
15
+ const option = group?.options?.[0];
16
+ if (!option) return undefined;
17
+
18
+ return {
19
+ name: option.translated.name,
20
+ mediaUrl: option.media?.url,
21
+ isImage: (group?.displayType ?? group?.translated.displayType) === "media",
22
+ };
23
+ });
24
+ </script>
25
+
26
+ <template>
27
+ <NuxtImg
28
+ v-if="kitchen?.isImage && kitchen.mediaUrl"
29
+ :src="kitchen.mediaUrl"
30
+ :alt="kitchen.name"
31
+ class="h-4 w-4 object-contain"
32
+ />
33
+ <span v-else-if="kitchen">{{ kitchen.name }}</span>
34
+ </template>
@@ -11,42 +11,9 @@ export type ShortcutFilterParam = {
11
11
  value: string | string[] | undefined;
12
12
  };
13
13
 
14
- const DEFAULT_CRITERIA: CategoryListingCriteria = {
15
- includes: {
16
- product: [
17
- "id",
18
- "productNumber",
19
- "name",
20
- "description",
21
- "calculatedPrice",
22
- "translated",
23
- "properties",
24
- "propertyIds",
25
- "sortedProperties",
26
- "cover",
27
- ],
28
- property: ["id", "name", "translated", "options"],
29
- property_group_option: ["id", "name", "translated", "group"],
30
- product_option: ["id", "groupId", "name", "translated", "group"],
31
- },
32
- associations: {
33
- cover: {
34
- associations: {
35
- media: {},
36
- },
37
- },
38
- properties: {
39
- associations: {
40
- group: {},
41
- },
42
- },
43
- },
44
- limit: 100,
45
- };
46
-
47
14
  export function useCategoryListing(
48
15
  categoryId: string,
49
- _defaultCriteria: CategoryListingCriteria = DEFAULT_CRITERIA,
16
+ initialProperties: string[] = [],
50
17
  ) {
51
18
  const nuxtApp = useNuxtApp();
52
19
 
@@ -71,7 +38,12 @@ export function useCategoryListing(
71
38
 
72
39
  const { data: listing, pending } = useLazyAsyncData(
73
40
  `listing-${categoryId}`,
74
- () => fetchListing({}),
41
+ () =>
42
+ fetchListing(
43
+ initialProperties.length > 0
44
+ ? { properties: initialProperties.join("|") }
45
+ : {},
46
+ ),
75
47
  );
76
48
 
77
49
  // Suppress skeleton during SSR hydration to prevent hydration mismatch.
@@ -0,0 +1,66 @@
1
+ import type { Schemas } from "#shopware";
2
+ import type { NitroFetchRequest } from "nitropack";
3
+
4
+ export function useListingSearch(initialQuery: string) {
5
+ const nuxtApp = useNuxtApp();
6
+ const loading = ref(false);
7
+ let currentController: AbortController | null = null;
8
+
9
+ async function fetchSearch(
10
+ query: string,
11
+ order?: string,
12
+ signal?: AbortSignal,
13
+ ): Promise<Schemas["ProductListingResult"]> {
14
+ return await $fetch("/api/search" as NitroFetchRequest, {
15
+ query: {
16
+ query,
17
+ ...(order && { order }),
18
+ },
19
+ signal,
20
+ });
21
+ }
22
+
23
+ const hasInitialQuery = initialQuery.trim().length > 0;
24
+
25
+ const { data: listing, pending } = useLazyAsyncData(
26
+ `search-${initialQuery}`,
27
+ () => fetchSearch(initialQuery),
28
+ {
29
+ immediate: hasInitialQuery,
30
+ },
31
+ );
32
+
33
+ const showSkeleton = computed(() => pending.value && !nuxtApp.isHydrating);
34
+ const elements = computed(() => listing.value?.elements ?? []);
35
+ const sortingOrders = computed(() => listing.value?.availableSortings);
36
+ const currentSortingOrder = computed(() => listing.value?.sorting);
37
+
38
+ async function applySearch(query: string, order?: string) {
39
+ currentController?.abort();
40
+ currentController = new AbortController();
41
+ const { signal } = currentController;
42
+
43
+ loading.value = true;
44
+ try {
45
+ listing.value = await fetchSearch(query, order, signal);
46
+ } catch (e) {
47
+ if ((e as { name?: string }).name !== "AbortError") throw e;
48
+ } finally {
49
+ loading.value = false;
50
+ }
51
+ }
52
+
53
+ async function changeSorting(order: string, query: string) {
54
+ await applySearch(query, order);
55
+ }
56
+
57
+ return {
58
+ showSkeleton,
59
+ loading,
60
+ elements,
61
+ sortingOrders,
62
+ currentSortingOrder,
63
+ applySearch,
64
+ changeSorting,
65
+ };
66
+ }
@@ -53,10 +53,21 @@ export function useTrackEvent() {
53
53
  ]);
54
54
  }
55
55
 
56
+ function trackSearch(term: string, productNumbers: string[]) {
57
+ proxy._paq.push([
58
+ "trackEvent",
59
+ "Search",
60
+ term,
61
+ productNumbers.join(","),
62
+ productNumbers.length,
63
+ ]);
64
+ }
65
+
56
66
  return {
57
67
  trackProductView,
58
68
  trackOrder,
59
69
  trackAddToWishlist,
60
70
  trackAddToCart,
71
+ trackSearch,
61
72
  };
62
73
  }
@@ -0,0 +1,177 @@
1
+ <script setup lang="ts">
2
+ import type { Schemas } from "#shopware";
3
+ import type { NitroFetchRequest } from "nitropack";
4
+
5
+ definePageMeta({
6
+ layout: "listing",
7
+ });
8
+
9
+ const route = useRoute();
10
+ const router = useRouter();
11
+ const { searchFallbackCategoryId } = useRuntimeConfig().public.shopBite;
12
+
13
+ const searchQuery = computed(() => String(route.query.q ?? "").trim());
14
+
15
+ const {
16
+ showSkeleton,
17
+ loading,
18
+ elements,
19
+ sortingOrders,
20
+ currentSortingOrder,
21
+ applySearch,
22
+ changeSorting,
23
+ } = useListingSearch(searchQuery.value);
24
+
25
+ const { trackSearch } = useTrackEvent();
26
+
27
+ // Re-fetch when the URL query changes (e.g. user searches again from this page)
28
+ watch(searchQuery, (q) => applySearch(q));
29
+
30
+ // Fire a Matomo event whenever results settle for a given search term
31
+ watch(elements, (products) => {
32
+ if (!searchQuery.value || showSkeleton.value) return;
33
+ trackSearch(
34
+ searchQuery.value,
35
+ products.map((p) => p.productNumber),
36
+ );
37
+ });
38
+
39
+ // Fallback: fetch a curated category listing when search returns no results.
40
+ // The category should have a dynamic product group assigned in Shopware.
41
+ const showFallback = computed(
42
+ () =>
43
+ !showSkeleton.value &&
44
+ !loading.value &&
45
+ elements.value.length === 0 &&
46
+ !!searchFallbackCategoryId,
47
+ );
48
+
49
+ const { data: fallbackProducts, refresh: refreshFallback } = useLazyAsyncData<
50
+ Schemas["Product"][]
51
+ >(
52
+ "search-fallback-listing",
53
+ async () => {
54
+ const result = await $fetch(
55
+ `/api/listing/${searchFallbackCategoryId}` as NitroFetchRequest,
56
+ );
57
+ return (result as { elements?: Schemas["Product"][] }).elements ?? [];
58
+ },
59
+ { immediate: false },
60
+ );
61
+
62
+ watch(showFallback, (visible) => {
63
+ if (visible && !fallbackProducts.value) {
64
+ refreshFallback();
65
+ }
66
+ });
67
+
68
+ const currentSorting = ref(currentSortingOrder.value ?? "Sortieren");
69
+
70
+ watch(currentSortingOrder, (val) => {
71
+ if (val) currentSorting.value = val;
72
+ });
73
+
74
+ watch(currentSorting, async (val) => {
75
+ if (val === currentSortingOrder.value) return;
76
+ await changeSorting(val, searchQuery.value);
77
+ });
78
+
79
+ const searchInput = ref(searchQuery.value);
80
+
81
+ function submitSearch() {
82
+ const term = searchInput.value.trim();
83
+ if (!term) return;
84
+ router.push({ path: "/suche", query: { q: term } });
85
+ }
86
+ </script>
87
+
88
+ <template>
89
+ <UContainer>
90
+ <UPage>
91
+ <UPageBody>
92
+ <div class="flex flex-col gap-4">
93
+ <div class="flex flex-col sm:flex-row gap-4">
94
+ <UInput
95
+ v-model="searchInput"
96
+ name="search"
97
+ class="flex-1"
98
+ size="md"
99
+ icon="i-lucide-search"
100
+ placeholder="Produkte suchen..."
101
+ @keyup.enter="submitSearch"
102
+ >
103
+ <template v-if="searchInput" #trailing>
104
+ <UButton
105
+ color="neutral"
106
+ variant="link"
107
+ size="sm"
108
+ icon="i-lucide-circle-x"
109
+ aria-label="Suche leeren"
110
+ @click="searchInput = ''"
111
+ />
112
+ </template>
113
+ </UInput>
114
+ <USelect
115
+ v-model="currentSorting"
116
+ icon="i-lucide-arrow-down-wide-narrow"
117
+ value-key="key"
118
+ :items="sortingOrders"
119
+ placeholder="Sortierung"
120
+ />
121
+ </div>
122
+
123
+ <div
124
+ v-if="searchQuery && !showSkeleton"
125
+ class="flex items-center gap-2"
126
+ >
127
+ <p class="text-sm text-muted">
128
+ Suchergebnisse für „{{ searchQuery }}"
129
+ </p>
130
+ <UBadge variant="subtle" :label="`${elements.length} Produkte`" />
131
+ </div>
132
+
133
+ <div
134
+ v-if="showSkeleton"
135
+ class="flex flex-col gap-4"
136
+ aria-busy="true"
137
+ aria-label="Produkte werden geladen"
138
+ >
139
+ <LazyProductCardSkeleton v-for="i in 6" :key="i" />
140
+ </div>
141
+
142
+ <div
143
+ v-else-if="elements.length > 0"
144
+ class="flex flex-col gap-4 transition-opacity duration-200"
145
+ :class="{ 'opacity-40 pointer-events-none': loading }"
146
+ >
147
+ <ProductCard
148
+ v-for="product in elements"
149
+ :key="product.id"
150
+ :product="product"
151
+ :with-favorite-button="true"
152
+ :with-add-to-cart-button="true"
153
+ />
154
+ </div>
155
+
156
+ <template v-else-if="searchQuery && !showSkeleton && !loading">
157
+ <p class="text-muted">
158
+ Keine Produkte für „{{ searchQuery }}" gefunden.
159
+ </p>
160
+ <template v-if="showFallback && fallbackProducts?.length">
161
+ <p class="text-sm font-medium mt-2">Das könnte dir gefallen:</p>
162
+ <div class="flex flex-col gap-4">
163
+ <ProductCard
164
+ v-for="product in fallbackProducts"
165
+ :key="product.id"
166
+ :product="product"
167
+ :with-favorite-button="true"
168
+ :with-add-to-cart-button="true"
169
+ />
170
+ </div>
171
+ </template>
172
+ </template>
173
+ </div>
174
+ </UPageBody>
175
+ </UPage>
176
+ </UContainer>
177
+ </template>
package/nuxt.config.ts CHANGED
@@ -63,6 +63,7 @@ export default defineNuxtConfig({
63
63
  category: 86400,
64
64
  },
65
65
  menuCategoryId: "",
66
+ searchFallbackCategoryId: "",
66
67
  feature: {
67
68
  multiChannel: false,
68
69
  secureKey: "",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shopbite-de/storefront",
3
- "version": "1.21.1",
3
+ "version": "1.22.0",
4
4
  "main": "nuxt.config.ts",
5
5
  "description": "Shopware storefront for food delivery shops",
6
6
  "keywords": [
@@ -18,8 +18,15 @@ const BASE_CRITERIA = {
18
18
  "sortedProperties",
19
19
  "cover",
20
20
  ],
21
- property: ["id", "name", "translated", "options"],
22
- property_group_option: ["id", "name", "translated", "group"],
21
+ property: ["id", "name", "translated", "displayType", "options"],
22
+ property_group_option: [
23
+ "id",
24
+ "name",
25
+ "translated",
26
+ "group",
27
+ "media",
28
+ "mediaId",
29
+ ],
23
30
  product_option: ["id", "groupId", "name", "translated", "group"],
24
31
  },
25
32
  associations: {
@@ -31,6 +38,7 @@ const BASE_CRITERIA = {
31
38
  properties: {
32
39
  associations: {
33
40
  group: {},
41
+ media: {},
34
42
  },
35
43
  },
36
44
  },
@@ -0,0 +1,99 @@
1
+ import type { components } from "~~/api-types/storeApiTypes";
2
+
3
+ type Schemas = components["schemas"];
4
+
5
+ const BASE_CRITERIA = {
6
+ includes: {
7
+ product: [
8
+ "id",
9
+ "productNumber",
10
+ "name",
11
+ "description",
12
+ "calculatedPrice",
13
+ "translated",
14
+ "properties",
15
+ "propertyIds",
16
+ "sortedProperties",
17
+ "cover",
18
+ ],
19
+ property: ["id", "name", "translated", "displayType", "options"],
20
+ property_group_option: [
21
+ "id",
22
+ "name",
23
+ "translated",
24
+ "group",
25
+ "media",
26
+ "mediaId",
27
+ ],
28
+ product_option: ["id", "groupId", "name", "translated", "group"],
29
+ },
30
+ associations: {
31
+ cover: {
32
+ associations: {
33
+ media: {},
34
+ },
35
+ },
36
+ properties: {
37
+ associations: {
38
+ group: {},
39
+ media: {},
40
+ },
41
+ },
42
+ },
43
+ limit: 100,
44
+ };
45
+
46
+ function sanitizeString(value: unknown, maxLength: number): string | undefined {
47
+ if (typeof value !== "string" || value === "") return undefined;
48
+ const trimmed = value.trim();
49
+ return trimmed.length <= maxLength ? trimmed : undefined;
50
+ }
51
+
52
+ function sanitizePage(value: unknown): number | undefined {
53
+ const n = Number(value);
54
+ return Number.isInteger(n) && n >= 1 && n <= 1000 ? n : undefined;
55
+ }
56
+
57
+ export default defineCachedEventHandler(
58
+ async (event) => {
59
+ const { endpoint, accessToken } = useRuntimeConfig().public.shopware;
60
+ const q = getQuery(event) as Record<string, unknown>;
61
+
62
+ const search = sanitizeString(q.query, 256);
63
+ const order = sanitizeString(q.order, 64);
64
+ const p = sanitizePage(q.p);
65
+
66
+ if (!search) {
67
+ return {
68
+ elements: [],
69
+ aggregations: {},
70
+ availableSortings: [],
71
+ } as unknown as Schemas["ProductListingResult"];
72
+ }
73
+
74
+ return await $fetch(`${endpoint}/search`, {
75
+ method: "POST",
76
+ headers: {
77
+ "sw-access-key": accessToken,
78
+ "sw-include-seo-urls": "true",
79
+ },
80
+ body: {
81
+ search,
82
+ ...BASE_CRITERIA,
83
+ ...(order && { order }),
84
+ ...(p && { p }),
85
+ },
86
+ });
87
+ },
88
+ {
89
+ maxAge: useRuntimeConfig().public.shopBite.cacheTtl.listing,
90
+ name: "search",
91
+ getKey: (event) => {
92
+ const q = getQuery(event) as Record<string, unknown>;
93
+ const search = sanitizeString(q.query, 256) ?? "";
94
+ const order = sanitizeString(q.order, 64) ?? "";
95
+ const p = sanitizePage(q.p) ?? 1;
96
+ return [search, order, p].join("|");
97
+ },
98
+ },
99
+ );
@@ -0,0 +1,218 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
+ import { flushPromises } from "@vue/test-utils";
3
+ import { mountSuspended } from "@nuxt/test-utils/runtime";
4
+ import { defineComponent, h } from "vue";
5
+ import { useCategoryListing } from "~/composables/useCategoryListing";
6
+
7
+ // ---- mock helpers ------------------------------------------------------------
8
+
9
+ const { mockFetch } = vi.hoisted(() => ({ mockFetch: vi.fn() }));
10
+
11
+ const emptyListing = (properties: string[] = []) => ({
12
+ elements: [],
13
+ aggregations: {},
14
+ availableSortings: [],
15
+ sorting: null,
16
+ currentFilters: { properties },
17
+ });
18
+
19
+ // ---- helpers ----------------------------------------------------------------
20
+
21
+ let categoryCounter = 0;
22
+ /** Returns a unique category ID per test to prevent useLazyAsyncData key collisions. */
23
+ const uniqueId = () => `cat-${++categoryCounter}`;
24
+
25
+ /**
26
+ * Mounts a minimal component that calls useCategoryListing so that
27
+ * useLazyAsyncData triggers the initial fetch (it only runs inside a
28
+ * component context).
29
+ */
30
+ async function mountWithListing(
31
+ categoryId: string,
32
+ initialProperties: string[] = [],
33
+ ) {
34
+ let result!: ReturnType<typeof useCategoryListing>;
35
+
36
+ await mountSuspended(
37
+ defineComponent({
38
+ setup() {
39
+ result = useCategoryListing(categoryId, initialProperties);
40
+ return () => h("div");
41
+ },
42
+ }),
43
+ );
44
+
45
+ await flushPromises();
46
+ return result;
47
+ }
48
+
49
+ // ---- tests ------------------------------------------------------------------
50
+
51
+ describe("useCategoryListing", () => {
52
+ beforeEach(() => {
53
+ vi.stubGlobal("$fetch", mockFetch);
54
+ mockFetch.mockResolvedValue(emptyListing());
55
+ });
56
+
57
+ afterEach(() => {
58
+ vi.unstubAllGlobals();
59
+ vi.clearAllMocks();
60
+ });
61
+
62
+ // ---- initial fetch (requires component context for useLazyAsyncData) ------
63
+
64
+ describe("initial fetch", () => {
65
+ it("fetches without properties when none are provided", async () => {
66
+ const id = uniqueId();
67
+ await mountWithListing(id);
68
+
69
+ expect(mockFetch).toHaveBeenCalledWith(
70
+ `/api/listing/${id}`,
71
+ expect.objectContaining({
72
+ query: expect.objectContaining({ properties: undefined }),
73
+ }),
74
+ );
75
+ });
76
+
77
+ it("fetches with persisted properties joined by pipe", async () => {
78
+ const id = uniqueId();
79
+ await mountWithListing(id, ["opt-a", "opt-b"]);
80
+
81
+ expect(mockFetch).toHaveBeenCalledWith(
82
+ `/api/listing/${id}`,
83
+ expect.objectContaining({
84
+ query: expect.objectContaining({ properties: "opt-a|opt-b" }),
85
+ }),
86
+ );
87
+ });
88
+
89
+ it("does not include properties param when initialProperties is empty", async () => {
90
+ const id = uniqueId();
91
+ await mountWithListing(id, []);
92
+
93
+ expect(mockFetch).toHaveBeenCalledWith(
94
+ `/api/listing/${id}`,
95
+ expect.objectContaining({
96
+ query: expect.objectContaining({ properties: undefined }),
97
+ }),
98
+ );
99
+ });
100
+ });
101
+
102
+ // ---- setFilters ------------------------------------------------------------
103
+
104
+ describe("setFilters", () => {
105
+ it("re-fetches with the given property filter", async () => {
106
+ const { setFilters } = useCategoryListing("cat-1");
107
+
108
+ await setFilters([{ code: "properties", value: "opt-x|opt-y" }]);
109
+
110
+ expect(mockFetch).toHaveBeenLastCalledWith(
111
+ "/api/listing/cat-1",
112
+ expect.objectContaining({
113
+ query: expect.objectContaining({ properties: "opt-x|opt-y" }),
114
+ }),
115
+ );
116
+ });
117
+
118
+ it("sets loading true during fetch and false after", async () => {
119
+ let resolve!: (v: unknown) => void;
120
+ const { setFilters, loading } = useCategoryListing("cat-1");
121
+
122
+ mockFetch.mockReturnValueOnce(new Promise((r) => (resolve = r)));
123
+ const promise = setFilters([{ code: "properties", value: "opt-x" }]);
124
+
125
+ expect(loading.value).toBe(true);
126
+ resolve(emptyListing());
127
+ await promise;
128
+ expect(loading.value).toBe(false);
129
+ });
130
+
131
+ it("overwrites existing currentFilters properties with the new value", async () => {
132
+ mockFetch.mockResolvedValueOnce(emptyListing(["old-opt"]));
133
+ const { setFilters } = useCategoryListing("cat-1");
134
+
135
+ await setFilters([{ code: "properties", value: "new-opt" }]);
136
+
137
+ expect(mockFetch).toHaveBeenLastCalledWith(
138
+ "/api/listing/cat-1",
139
+ expect.objectContaining({
140
+ query: expect.objectContaining({ properties: "new-opt" }),
141
+ }),
142
+ );
143
+ });
144
+ });
145
+
146
+ // ---- resetFilters ----------------------------------------------------------
147
+
148
+ describe("resetFilters", () => {
149
+ it("re-fetches with all filter params cleared", async () => {
150
+ const { resetFilters } = useCategoryListing("cat-1", ["opt-a"]);
151
+
152
+ await resetFilters();
153
+
154
+ expect(mockFetch).toHaveBeenLastCalledWith(
155
+ "/api/listing/cat-1",
156
+ expect.objectContaining({
157
+ query: {
158
+ properties: undefined,
159
+ order: undefined,
160
+ manufacturer: undefined,
161
+ query: undefined,
162
+ p: undefined,
163
+ },
164
+ }),
165
+ );
166
+ });
167
+ });
168
+
169
+ // ---- changeSorting ---------------------------------------------------------
170
+
171
+ describe("changeSorting", () => {
172
+ it("re-fetches with the given sort order", async () => {
173
+ const { changeSorting } = useCategoryListing("cat-1");
174
+
175
+ await changeSorting("price-asc");
176
+
177
+ expect(mockFetch).toHaveBeenLastCalledWith(
178
+ "/api/listing/cat-1",
179
+ expect.objectContaining({
180
+ query: expect.objectContaining({ order: "price-asc" }),
181
+ }),
182
+ );
183
+ });
184
+ });
185
+
186
+ // ---- derived state ---------------------------------------------------------
187
+
188
+ describe("derived state", () => {
189
+ it("exposes elements from the listing response", async () => {
190
+ const products = [{ id: "p1" }, { id: "p2" }];
191
+ mockFetch.mockResolvedValueOnce({
192
+ ...emptyListing(),
193
+ elements: products,
194
+ });
195
+
196
+ const { elements, setFilters } = useCategoryListing(uniqueId());
197
+ await setFilters([]);
198
+ await flushPromises();
199
+
200
+ expect(elements.value).toEqual(products);
201
+ });
202
+
203
+ it("defaults elements to empty array before data loads", async () => {
204
+ const { elements } = useCategoryListing(uniqueId());
205
+ expect(elements.value).toEqual([]);
206
+ });
207
+
208
+ it("exposes currentFilters from the listing response", async () => {
209
+ mockFetch.mockResolvedValueOnce(emptyListing(["opt-x"]));
210
+
211
+ const { currentFilters, setFilters } = useCategoryListing(uniqueId());
212
+ await setFilters([]);
213
+ await flushPromises();
214
+
215
+ expect(currentFilters.value?.properties).toEqual(["opt-x"]);
216
+ });
217
+ });
218
+ });