@revenexx/cover 0.2.10 → 0.2.13

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.
@@ -1,4 +1,5 @@
1
1
  export const productsApi = {
2
2
  list: () => "/api/products",
3
3
  byId: (id: string) => `/api/products/${id}`,
4
+ facetMeta: () => "/api/products/facet-meta",
4
5
  };
@@ -4,25 +4,39 @@ import type { AccountNavGroup } from "../../config/navigation";
4
4
 
5
5
  const { icon } = useIcons();
6
6
 
7
- // Consumers can replace the full B2B navigation tree with their own
8
- // (e.g. a lean storefront theme exposing only orders + profile) via
9
- // app.config — `accountNavigation: AccountNavGroup[]`.
10
7
  const appConfig = useAppConfig();
11
8
  const navigation = computed<AccountNavGroup[]>(() =>
12
9
  (appConfig.accountNavigation as AccountNavGroup[] | undefined) ?? accountNavigation,
13
10
  );
14
11
 
15
- /**
16
- * The full B2B account navigation tree (structure from the relation
17
- * prototype). Implemented entries route to real pages, the rest leads to the
18
- * coming-soon catch-all — making the product roadmap explorable.
19
- */
20
12
  const { t } = useI18n();
21
13
  const localePath = useLocalePath();
22
14
  const route = useRoute();
23
15
  const auth = useAuthStore();
24
16
  const toast = useToast();
25
17
 
18
+ const isDrawerOpen = ref(false);
19
+ const drawerNavRef = ref<HTMLElement | null>(null);
20
+
21
+ const activeGroupLabel = computed(() => {
22
+ for (const group of navigation.value) {
23
+ if (group.links.some(link => isActive(link.to))) return t(group.labelKey);
24
+ }
25
+ return t("account.nav.groups.account");
26
+ });
27
+
28
+ watch(() => route.path, () => {
29
+ isDrawerOpen.value = false;
30
+ });
31
+
32
+ watch(isDrawerOpen, async (opened: boolean) => {
33
+ if (!opened) return;
34
+ await nextTick();
35
+ drawerNavRef.value
36
+ ?.querySelector<HTMLElement>("[data-group-active]")
37
+ ?.scrollIntoView({ block: "start", behavior: "instant" });
38
+ });
39
+
26
40
  async function onLogout(): Promise<void> {
27
41
  await auth.logout();
28
42
  toast.add({
@@ -34,6 +48,10 @@ async function onLogout(): Promise<void> {
34
48
  await navigateTo(localePath("/login"));
35
49
  }
36
50
 
51
+ function isGroupActive(group: AccountNavGroup): boolean {
52
+ return group.links.some(link => isActive(link.to));
53
+ }
54
+
37
55
  function isActive(to: string): boolean {
38
56
  const localized = localePath(to);
39
57
  if (to === "/account") {
@@ -44,9 +62,10 @@ function isActive(to: string): boolean {
44
62
  </script>
45
63
 
46
64
  <template>
65
+ <!-- Desktop sidebar -->
47
66
  <nav
48
67
  :aria-label="t('account.nav.groups.account')"
49
- class="w-full lg:w-72 shrink-0 bg-elevated rounded-lg px-6 py-2"
68
+ class="hidden lg:block w-72 shrink-0 bg-elevated rounded-lg px-6 py-2"
50
69
  >
51
70
  <ul class="divide-y divide-default">
52
71
  <li
@@ -82,7 +101,6 @@ function isActive(to: string): boolean {
82
101
  <li class="py-4">
83
102
  <button
84
103
  type="button"
85
- tabindex="0"
86
104
  class="flex items-center gap-2 py-1 text-sm text-error
87
105
  hover:text-highlighted transition-colors cursor-pointer"
88
106
  @click="onLogout"
@@ -96,4 +114,126 @@ function isActive(to: string): boolean {
96
114
  </li>
97
115
  </ul>
98
116
  </nav>
117
+
118
+ <!-- Mobile: trigger bar + drawer -->
119
+ <div class="lg:hidden">
120
+ <button
121
+ type="button"
122
+ class="w-full flex items-center justify-between bg-elevated rounded-lg px-4 py-3 text-sm
123
+ transition-colors hover:bg-accented cursor-pointer"
124
+ :aria-label="t('account.nav.open')"
125
+ @click="isDrawerOpen = true"
126
+ >
127
+ <span class="flex items-center gap-2 font-medium text-highlighted">
128
+ <UIcon
129
+ :name="icon('menu')"
130
+ class="size-4 text-primary"
131
+ />
132
+ {{ activeGroupLabel }}
133
+ </span>
134
+ <UIcon
135
+ :name="icon('chevron-right')"
136
+ class="size-4 text-muted"
137
+ />
138
+ </button>
139
+
140
+ <UDrawer
141
+ v-model:open="isDrawerOpen"
142
+ direction="left"
143
+ :ui="{ content: 'w-72 h-full flex flex-col' }"
144
+ >
145
+ <template #content>
146
+ <div class="flex items-center gap-3 px-5 py-5 border-b border-default shrink-0">
147
+ <div
148
+ class="size-10 rounded-full bg-primary flex items-center justify-center
149
+ text-inverted font-bold text-sm shrink-0"
150
+ aria-hidden="true"
151
+ >
152
+ {{ auth.user?.name?.[0]?.toUpperCase() ?? '?' }}
153
+ </div>
154
+ <div class="min-w-0">
155
+ <div class="font-semibold text-sm truncate text-highlighted">
156
+ {{ auth.user?.name }}
157
+ </div>
158
+ <div class="text-xs text-muted truncate">
159
+ {{ auth.user?.email }}
160
+ </div>
161
+ </div>
162
+ </div>
163
+
164
+ <nav
165
+ ref="drawerNavRef"
166
+ :aria-label="t('account.nav.groups.account')"
167
+ class="overflow-y-auto flex-1 px-4 py-2"
168
+ >
169
+ <ul class="divide-y divide-default">
170
+ <li
171
+ v-for="(group, groupIndex) in navigation"
172
+ :key="group.labelKey"
173
+ class="py-3"
174
+ :data-group-active="isGroupActive(group) ? '' : undefined"
175
+ >
176
+ <div class="text-xs font-semibold uppercase tracking-wider text-muted pb-1">
177
+ {{ t(group.labelKey) }}
178
+ </div>
179
+ <ul>
180
+ <li
181
+ v-for="(link, linkIndex) in group.links"
182
+ :key="link.to"
183
+ class="nav-item"
184
+ :style="{ animationDelay: `${(groupIndex * 5 + linkIndex) * 18}ms` }"
185
+ >
186
+ <NuxtLink
187
+ :to="localePath(link.to)"
188
+ class="flex items-center gap-2.5 py-1.5 text-sm transition-colors"
189
+ :class="isActive(link.to)
190
+ ? 'text-primary font-medium'
191
+ : 'text-muted hover:text-highlighted'"
192
+ >
193
+ <UIcon
194
+ :name="icon(link.icon)"
195
+ class="size-4 shrink-0"
196
+ :class="isActive(link.to) ? 'text-primary' : 'text-primary/70'"
197
+ />
198
+ {{ t(link.labelKey) }}
199
+ </NuxtLink>
200
+ </li>
201
+ </ul>
202
+ </li>
203
+ <li class="py-3">
204
+ <button
205
+ type="button"
206
+ class="flex items-center gap-2 py-1 text-sm text-error
207
+ hover:text-highlighted transition-colors cursor-pointer"
208
+ @click="onLogout"
209
+ >
210
+ <UIcon
211
+ :name="icon('logout')"
212
+ class="size-4 shrink-0"
213
+ />
214
+ {{ t('menu.logout') }}
215
+ </button>
216
+ </li>
217
+ </ul>
218
+ </nav>
219
+ </template>
220
+ </UDrawer>
221
+ </div>
99
222
  </template>
223
+
224
+ <style scoped>
225
+ @keyframes slide-in {
226
+ from {
227
+ opacity: 0;
228
+ transform: translateX(-10px);
229
+ }
230
+ to {
231
+ opacity: 1;
232
+ transform: translateX(0);
233
+ }
234
+ }
235
+
236
+ .nav-item {
237
+ animation: slide-in 0.22s ease-out both;
238
+ }
239
+ </style>
@@ -24,7 +24,7 @@ const { data: list, status, error, refresh } = useFetch<OrderList>(
24
24
  { key: `account-order-list:${props.listId}` },
25
25
  );
26
26
 
27
- const isOwner = computed(() => authStore.user?.$id === list.value?.owner.id);
27
+ const isOwner = computed(() => !!list.value && isOwnOrderList(list.value, authStore.user));
28
28
  const listValue = computed(() =>
29
29
  Math.round((list.value?.positions ?? []).reduce((sum, p) => sum + p.price * p.quantity, 0) * 100) / 100,
30
30
  );
@@ -6,7 +6,7 @@ const { viewMode } = useViewMode();
6
6
  <!-- Grid skeleton -->
7
7
  <div
8
8
  v-if="viewMode !== 'list'"
9
- class="mt-6 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4"
9
+ class="mt-6 grid grid-cols-1 sm:grid-cols-3 lg:grid-cols-4 gap-4"
10
10
  >
11
11
  <UCard
12
12
  v-for="i in 8"
@@ -29,7 +29,7 @@ function isActive(to: string): boolean {
29
29
  <template>
30
30
  <nav
31
31
  :aria-label="t('nav.mainNavigation')"
32
- class="bg-inverted text-inverted"
32
+ class="hidden md:block bg-inverted text-inverted"
33
33
  >
34
34
  <div
35
35
  class="px-4 sm:px-6 lg:px-8 max-w-(--ui-container) mx-auto w-full
@@ -1,4 +1,6 @@
1
1
  <script setup lang="ts">
2
+ import { mainNavigation as defaultMainNav } from "../../../config/navigation";
3
+
2
4
  const { icon } = useIcons();
3
5
 
4
6
  const { categoryNavItems } = useCategories();
@@ -6,6 +8,14 @@ const auth = useAuthStore();
6
8
  const toast = useToast();
7
9
  const { t } = useI18n();
8
10
  const localePath = useLocalePath();
11
+ const appConfig = useAppConfig();
12
+
13
+ const liveMain = useState<typeof defaultMainNav | null>("cover:nav:mainNavigation", () => null);
14
+
15
+ const mainNavItems = computed(() =>
16
+ (liveMain.value ?? (appConfig.mainNavigation as typeof defaultMainNav | undefined) ?? defaultMainNav)
17
+ .map(item => ({ label: t(item.labelKey), to: localePath(item.to) })),
18
+ );
9
19
 
10
20
  const accountLinks = computed(() => [
11
21
  { label: t("menu.profile"), icon: icon("user"), to: "/account", tabindex: 0 },
@@ -27,6 +37,13 @@ const onLogout = async () => {
27
37
 
28
38
  <template>
29
39
  <div class="flex flex-col gap-4 pb-4">
40
+ <UNavigationMenu
41
+ :items="mainNavItems"
42
+ orientation="vertical"
43
+ />
44
+
45
+ <USeparator />
46
+
30
47
  <div class="md:hidden">
31
48
  <UNavigationMenu
32
49
  :items="categoryNavItems"
@@ -30,7 +30,7 @@ function chipLabel(field: string, value: string): string {
30
30
  const listing = props.listing;
31
31
 
32
32
  const gridClasses = computed(() => viewMode.value === "grid"
33
- ? "grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4"
33
+ ? "grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4"
34
34
  : "flex flex-col gap-4");
35
35
 
36
36
  const listView = resolveComponent("CategoryViewListView");
@@ -53,7 +53,7 @@ const listsWithProduct = computed(() =>
53
53
 
54
54
  const onListNames = computed(() => listsWithProduct.value.map(list => list.name).join(", "));
55
55
 
56
- const isOwn = (list: OrderList): boolean => list.owner.id === auth.user?.$id;
56
+ const isOwn = (list: OrderList): boolean => isOwnOrderList(list, auth.user);
57
57
 
58
58
  const lastUsedList = computed(() =>
59
59
  (lists.value ?? []).find(list => list.id === lastUsedId.value && isOwn(list)) ?? null);
@@ -20,6 +20,7 @@ const emit = defineEmits<{
20
20
 
21
21
  const { icon } = useIcons();
22
22
  const { t } = useI18n();
23
+ const facetMeta = useFacetMeta();
23
24
 
24
25
  const FACET_VALUE_KEY_MAP: Record<string, Record<string, string>> = {
25
26
  available: {
@@ -68,10 +69,22 @@ function clearAll() {
68
69
  }
69
70
 
70
71
  function facetLabel(fieldName: string): string {
72
+ // Per-tenant dynamic facets come from the Products app's
73
+ // is_filterable attributes — labels live in the attribute meta,
74
+ // not the i18n bundle. Spine facets keep the i18n key path.
75
+ if (fieldName.startsWith("attrs.")) {
76
+ return facetMeta.label(fieldName.slice(6));
77
+ }
71
78
  return t(`search.filters.facets.${fieldName}`, fieldName);
72
79
  }
73
80
 
74
81
  function facetValueLabel(fieldName: string, value: string): string {
82
+ // Dynamic facet values: select-attribute options carry their own
83
+ // labels map (de/en); the doc stores the raw option code. Look up
84
+ // the localized label via the meta cache.
85
+ if (fieldName.startsWith("attrs.")) {
86
+ return facetMeta.valueLabel(fieldName.slice(6), value);
87
+ }
75
88
  const key = FACET_VALUE_KEY_MAP[fieldName]?.[value];
76
89
  return key ? t(key) : value;
77
90
  }
@@ -0,0 +1,80 @@
1
+ import { productsApi } from "../api/products";
2
+
3
+ /**
4
+ * Per-tenant Typesense facet metadata — the subset of product
5
+ * attributes the tenant has flipped `is_filterable=true` in the
6
+ * Products app. Mirrors the schema fields the search-admin facet
7
+ * syncer projects into the collection as `attrs.<code>`.
8
+ *
9
+ * Used by useProductListing to extend `facetFields` and by
10
+ * SearchFacets.vue to resolve a localized label for each
11
+ * `attrs.<code>` facet plus its option-coded values
12
+ * (e.g. `fusskammer` → "Fußkammer").
13
+ *
14
+ * Cached per tenant server-side via `loadLiveAttributeMeta` (5min);
15
+ * the client fetches once per page navigation and reuses across
16
+ * listing surfaces.
17
+ */
18
+ export interface FacetMetaEntry {
19
+ code: string;
20
+ type: string;
21
+ labels: Record<string, string>;
22
+ options: Record<string, Record<string, string>>;
23
+ position: number;
24
+ groupCode: string | null;
25
+ unit: string | null;
26
+ }
27
+
28
+ interface FacetMetaResponse {
29
+ facets: FacetMetaEntry[];
30
+ }
31
+
32
+ export function useFacetMeta() {
33
+ const { locale } = useI18n();
34
+
35
+ const { data, status, error } = useFetch<FacetMetaResponse>(productsApi.facetMeta(), {
36
+ key: "facet-meta",
37
+ headers: computed(() => ({ "x-locale": locale.value })),
38
+ default: () => ({ facets: [] }),
39
+ });
40
+
41
+ /** All filterable codes in display order (by position). */
42
+ const codes = computed<string[]>(() => (data.value?.facets ?? []).map(f => f.code));
43
+
44
+ /** code → entry, for fast lookups in label/value resolvers. */
45
+ const byCode = computed<Map<string, FacetMetaEntry>>(() => {
46
+ const m = new Map<string, FacetMetaEntry>();
47
+ for (const f of data.value?.facets ?? []) {
48
+ m.set(f.code, f);
49
+ }
50
+ return m;
51
+ });
52
+
53
+ /**
54
+ * Resolve a localized label for a facet whose Typesense field name
55
+ * is `attrs.<code>`. Falls back to `en`, then to the raw code so
56
+ * the UI never renders an empty header.
57
+ */
58
+ function label(code: string): string {
59
+ const entry = byCode.value.get(code);
60
+ if (!entry) return code;
61
+ return entry.labels[locale.value] ?? entry.labels.en ?? code;
62
+ }
63
+
64
+ /**
65
+ * Resolve a localized label for a value of an `attrs.<code>` facet.
66
+ * For select/multiselect attributes the stored value equals the
67
+ * option `code`; we look up that option's labels map. For
68
+ * non-option types (or unknown values) we return the raw value
69
+ * unchanged.
70
+ */
71
+ function valueLabel(code: string, value: string): string {
72
+ const entry = byCode.value.get(code);
73
+ if (!entry) return value;
74
+ const optionLabels = entry.options[value];
75
+ if (!optionLabels) return value;
76
+ return optionLabels[locale.value] ?? optionLabels.en ?? value;
77
+ }
78
+
79
+ return { codes, byCode, label, valueLabel, status, error };
80
+ }
@@ -0,0 +1,22 @@
1
+ import type { AuthUser } from "../interfaces/auth";
2
+ import type { OrderList } from "../interfaces/account/order-lists";
3
+
4
+ /**
5
+ * Whether the signed-in user owns an order list.
6
+ *
7
+ * The cover `OrderList.owner.id` is NOT one stable identity across data modes:
8
+ * in live mode the orderlists app keys lists by the **contact** id
9
+ * (`owner_id = contactId`), while the mock service stores the platform **user**
10
+ * id (`user.$id`). The auth user carries both, so match either — comparing only
11
+ * against `$id` silently failed in live (contactId ≠ $id), which made every
12
+ * list look un-owned and disabled the "add to an existing list" toggles.
13
+ */
14
+ export function isOwnOrderList(
15
+ list: Pick<OrderList, "owner">,
16
+ user: Pick<AuthUser, "$id" | "contactId"> | null | undefined,
17
+ ): boolean {
18
+ if (!user) {
19
+ return false;
20
+ }
21
+ return list.owner.id === user.$id || (!!user.contactId && list.owner.id === user.contactId);
22
+ }
@@ -39,7 +39,16 @@ export function useProductListing(options: ProductListingOptions) {
39
39
  const { t } = useI18n();
40
40
  const { productsPerPage } = useRuntimeConfig().public;
41
41
 
42
- const facetFields = options.facetFields ?? DEFAULT_FACETS;
42
+ // Static facets (configured by the calling page) plus dynamic
43
+ // per-tenant `attrs.<code>` facets from the Products app's
44
+ // `is_filterable` flags. The dynamic side reacts to the SSR-loaded
45
+ // useFacetMeta payload — first render already includes them.
46
+ const staticFacets = options.facetFields ?? DEFAULT_FACETS;
47
+ const facetMeta = useFacetMeta();
48
+ const facetFields = computed(() => [
49
+ ...staticFacets,
50
+ ...facetMeta.codes.value.map(c => `attrs.${c}`),
51
+ ]);
43
52
  const query = computed(() => options.query?.() ?? "");
44
53
 
45
54
  /* ---- URL state ---------------------------------------------------- */
@@ -78,7 +87,7 @@ export function useProductListing(options: ProductListingOptions) {
78
87
  const activeFilters = computed<Record<string, string[]>>({
79
88
  get() {
80
89
  const result: Record<string, string[]> = {};
81
- for (const field of facetFields) {
90
+ for (const field of facetFields.value) {
82
91
  const raw = route.query[field] as string | undefined;
83
92
  if (raw) {
84
93
  result[field] = raw.split(",").filter(Boolean);
@@ -88,7 +97,7 @@ export function useProductListing(options: ProductListingOptions) {
88
97
  },
89
98
  set(filters: Record<string, string[]>) {
90
99
  const updates: Record<string, string | null> = {};
91
- for (const field of facetFields) {
100
+ for (const field of facetFields.value) {
92
101
  const values = filters[field];
93
102
  updates[field] = values?.length ? values.join(",") : null;
94
103
  }
@@ -164,7 +173,7 @@ export function useProductListing(options: ProductListingOptions) {
164
173
  /** Facets in configured order, slug facets hidden from the UI. */
165
174
  const facets = computed<SearchFacet[]>(() => {
166
175
  const byField = new Map((data.value?.facets ?? []).map(f => [f.fieldName, f]));
167
- return facetFields
176
+ return facetFields.value
168
177
  .map(field => byField.get(field))
169
178
  .filter((f): f is SearchFacet => Boolean(f && f.counts.length > 0));
170
179
  });
@@ -194,7 +203,7 @@ export function useProductListing(options: ProductListingOptions) {
194
203
 
195
204
  function clearFilters() {
196
205
  const updates: Record<string, null> = { price_min: null, price_max: null };
197
- for (const field of facetFields) {
206
+ for (const field of facetFields.value) {
198
207
  updates[field] = null;
199
208
  }
200
209
  updateUrl(updates);
@@ -96,7 +96,7 @@ export const mainNavigation: NavItem[] = [
96
96
  export const mainNavigationSecondary: NavItem[] = [
97
97
  { labelKey: "header.projects", to: "/account/projects" },
98
98
  { labelKey: "header.orderLists", to: "/account/order-lists" },
99
- { labelKey: "topbar.orderStatus", to: "/account/orders" },
99
+ { labelKey: "topbar.orderOrders", to: "/account/orders" },
100
100
  ];
101
101
 
102
102
  export interface AccountNavLink {
@@ -182,6 +182,7 @@
182
182
  "integrations": "Schnittstellen",
183
183
  "settings": "Einstellungen"
184
184
  },
185
+ "open": "Kontonavigation öffnen",
185
186
  "dashboard": "Dashboard",
186
187
  "carts": "Warenkörbe",
187
188
  "orderTemplates": "Bestellvorlagen",
@@ -36,7 +36,7 @@
36
36
  "freeShipping": "Versandkostenfrei ab 100 € Bestellwert",
37
37
  "nextDayDelivery": "Bis 16:00 Uhr bestellt. Am nächsten Tag geliefert.",
38
38
  "directOrder": "Direktbestellung",
39
- "orderStatus": "Auftragsstatus",
39
+ "orderOrders": "Bestellungen",
40
40
  "localeSelector": "Deutschland (Deutsch) in €",
41
41
  "switchLocale": "Sprache und Region wählen",
42
42
  "contact": "Kontakt",
@@ -182,6 +182,7 @@
182
182
  "integrations": "Integrations",
183
183
  "settings": "Settings"
184
184
  },
185
+ "open": "Open account navigation",
185
186
  "dashboard": "Dashboard",
186
187
  "carts": "Carts",
187
188
  "orderTemplates": "Order templates",
@@ -36,7 +36,7 @@
36
36
  "freeShipping": "Free shipping on orders over €100",
37
37
  "nextDayDelivery": "Ordered by 4 pm. Delivered the next day.",
38
38
  "directOrder": "Direct order",
39
- "orderStatus": "Order status",
39
+ "orderOrders": "Orders",
40
40
  "localeSelector": "Germany (German) in €",
41
41
  "switchLocale": "Choose language and region",
42
42
  "contact": "Contact",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@revenexx/cover",
3
- "version": "0.2.10",
4
- "description": "Cover — revenexx design system for Nuxt. Distributed as a Nuxt layer: generic UI components, theming tokens and stores shared by the demo shop, custom storefronts and the Blokkli theme.",
3
+ "version": "0.2.13",
4
+ "description": "Cover \u2014 revenexx design system for Nuxt. Distributed as a Nuxt layer: generic UI components, theming tokens and stores shared by the demo shop, custom storefronts and the Blokkli theme.",
5
5
  "type": "module",
6
6
  "main": "./nuxt.config.ts",
7
7
  "license": "MIT",
@@ -38,7 +38,7 @@
38
38
  "@formkit/vue": "^1.6.0",
39
39
  "@iconify-json/lucide": "^1.2.111",
40
40
  "@internationalized/date": "^3.12.0",
41
- "@revenexx/sdk": "^0.0.12",
41
+ "@revenexx/sdk": "^0.0.15",
42
42
  "@revenexx/storage-model-viewer": "^0.3.0",
43
43
  "@vueuse/core": "^14.3.0",
44
44
  "typesense": "^3.0.5"
@@ -0,0 +1,57 @@
1
+ import { loadLiveAttributeMeta } from "../../utils/liveCatalog";
2
+
3
+ /**
4
+ * Subset of product-attribute metadata used by the storefront to build
5
+ * per-tenant Typesense facets. Includes only attributes the tenant has
6
+ * marked `is_filterable=true` — the same flag the search-admin facet
7
+ * syncer uses to decide which `attrs.<code>` fields to project into the
8
+ * Typesense schema. Cached server-side via the existing
9
+ * `loadLiveAttributeMeta` cache (5min, tenant-keyed).
10
+ *
11
+ * Shape per entry — locale-agnostic; the consumer picks the right
12
+ * label by `useI18n().locale`:
13
+ *
14
+ * {
15
+ * code: "compatible_cooler_type",
16
+ * type: "select",
17
+ * labels: { de: "Passend für Kühlertyp", en: "Compatible cooler type" },
18
+ * options: { fusskammer: { de: "Fußkammer", en: "Footwell" }, … },
19
+ * position: 12,
20
+ * groupCode: "technical",
21
+ * unit: null
22
+ * }
23
+ */
24
+ export interface FacetMetaEntry {
25
+ code: string;
26
+ type: string;
27
+ labels: Record<string, string>;
28
+ options: Record<string, Record<string, string>>;
29
+ position: number;
30
+ groupCode: string | null;
31
+ unit: string | null;
32
+ }
33
+
34
+ export default defineEventHandler(async (): Promise<{ facets: FacetMetaEntry[] }> => {
35
+ try {
36
+ const meta = await loadLiveAttributeMeta();
37
+
38
+ const facets: FacetMetaEntry[] = Object.entries(meta)
39
+ .filter(([, m]) => m.isFilterable && !m.hidden)
40
+ .map(([code, m]) => ({
41
+ code,
42
+ type: m.type,
43
+ labels: m.labels ?? {},
44
+ options: m.options,
45
+ position: m.position,
46
+ groupCode: m.groupCode,
47
+ unit: m.unit,
48
+ }))
49
+ .sort((a, b) => a.position - b.position);
50
+
51
+ return { facets };
52
+ }
53
+ catch (err) {
54
+ getLogService().error("Service error: products/facet-meta", toErrorContext(err));
55
+ throw createError({ statusCode: 500, message: "Internal server error" });
56
+ }
57
+ });
@@ -1,6 +1,7 @@
1
1
  import type { ProductList } from "../../../app/interfaces/product-list";
2
2
  import type { SearchFacet } from "../../../app/interfaces/search-facets";
3
3
 
4
+ import { loadLiveAttributeMeta } from "../../utils/liveCatalog";
4
5
  import { FACET_FIELDS, PRODUCTS_COLLECTION } from "../../utils/productsSchema";
5
6
 
6
7
  type SortOption = "relevance" | "price_asc" | "price_desc" | "name_asc" | "name_desc";
@@ -43,6 +44,16 @@ export default defineEventHandler(async (event) => {
43
44
  const locale = resolveLocale(event);
44
45
  const liveFilterParts = [`locale:=${tsFilterValue(locale)}`, "enabled:=true"];
45
46
 
47
+ // Per-tenant dynamic facets: the search-admin facet syncer mirrors
48
+ // every `is_filterable=true` attribute into the Typesense schema
49
+ // as `attrs.<code>`. We surface those codes here so the live
50
+ // branch can both forward `attrs.*` filter values AND ask
51
+ // Typesense to compute facet counts on them.
52
+ const attrMeta = await loadLiveAttributeMeta().catch(() => ({}));
53
+ const filterableCodes = Object.entries(attrMeta)
54
+ .filter(([, m]) => m.isFilterable && !m.hidden)
55
+ .map(([code]) => code);
56
+
46
57
  if (filters) {
47
58
  // The storefront filters with the demo-schema field names; the
48
59
  // live collection (search.json) names them differently. Category
@@ -69,6 +80,13 @@ export default defineEventHandler(async (event) => {
69
80
  // enabled:=true is already pinned; an explicit "false" can
70
81
  // never match — keep the pinned filter authoritative.
71
82
  }
83
+ else if (field.startsWith("attrs.") && filterableCodes.includes(field.slice(6))) {
84
+ // Tenant-defined attribute filter. Only honour codes the
85
+ // attribute meta knows about — protects against URL
86
+ // tampering that could spam Typesense with bogus filter
87
+ // fields (Typesense 400s on unknown filter_by paths).
88
+ liveFilterParts.push(`${field}:=[${values.map(v => tsFilterValue(v)).join(",")}]`);
89
+ }
72
90
  }
73
91
 
74
92
  if (categoryCodes.length) {
@@ -76,14 +94,22 @@ export default defineEventHandler(async (event) => {
76
94
  }
77
95
  }
78
96
 
97
+ // Spine facets + tenant-defined dynamic facets. category_labels is
98
+ // locale-templated and not a facet in the deployed schema —
99
+ // `categories` (codes) is the stable facet.
100
+ const liveFacetBy = [
101
+ "manufacturer",
102
+ "kind",
103
+ "categories",
104
+ ...filterableCodes.map(c => `attrs.${c}`),
105
+ ].join(",");
106
+
79
107
  try {
80
108
  const results = await searchLiveProducts({
81
109
  q,
82
110
  queryBy: "name,sku,description,manufacturer",
83
111
  filterBy: liveFilterParts.join(" && "),
84
- // category_labels is a locale-templated field and not a facet in
85
- // the deployed schema — categories (codes) is the stable facet.
86
- facetBy: "manufacturer,kind,categories",
112
+ facetBy: liveFacetBy,
87
113
  page,
88
114
  perPage,
89
115
  });
@@ -97,13 +97,17 @@ export function mapLiveDocToProduct(doc: LiveProductDoc): Product {
97
97
  prices: [],
98
98
  stocks: [],
99
99
  tax: { rate: LIVE_DEFAULT_TAX_RATE },
100
- image: PRODUCT_PLACEHOLDER_IMAGE,
100
+ // The product's image is a common attribute (search.json `attribute:common.*`
101
+ // catch-all → the doc's `attrs` object). Pass it through (full URL or a
102
+ // storage key the theme's image provider resolves); fall back to the
103
+ // placeholder when the product declares none.
104
+ image: typeof doc.attrs?.image === "string" && doc.attrs.image ? doc.attrs.image : PRODUCT_PLACEHOLDER_IMAGE,
101
105
  category,
102
106
  categorySlug,
103
107
  };
104
108
  }
105
109
 
106
- export function mapLiveDocToDetail(doc: LiveProductDoc): ProductDetail {
110
+ export async function mapLiveDocToDetail(doc: LiveProductDoc, locale: Locale = "de"): Promise<ProductDetail> {
107
111
  const syncedAt = doc.updated_at ? new Date(doc.updated_at * 1000).toISOString() : new Date().toISOString();
108
112
 
109
113
  return {
@@ -128,11 +132,12 @@ export function mapLiveDocToDetail(doc: LiveProductDoc): ProductDetail {
128
132
  ...(doc.categories?.[0] ? [{ type: "slug", name: doc.categories[0] }] : []),
129
133
  ],
130
134
  images: [],
131
- attributes: Object.entries(doc.attrs ?? {}).map(([name, value], index) => ({
132
- id: index + 1,
133
- name,
134
- value: String(value),
135
- })),
135
+ // Specifications: the `attrs` catch-all holds the product's common
136
+ // attributes as raw key→value. Resolve each through the products app's
137
+ // attribute definitions so the storefront shows the localized LABEL
138
+ // (never the technical code), select values as their option label, a
139
+ // unit suffix where declared, and hides internal/media keys (e.g. image).
140
+ attributes: await buildSpecRows(doc.attrs ?? {}, locale),
136
141
  prices: [],
137
142
  };
138
143
  }
@@ -245,3 +250,137 @@ export async function getLiveCategories(locale: Locale): Promise<ProductCategory
245
250
  })),
246
251
  }));
247
252
  }
253
+
254
+ // ---------------------------------------------------------------------------
255
+ // Attribute metadata — resolves the storefront specification table's raw
256
+ // attribute keys to localized labels, select-option labels and unit suffixes
257
+ // (from the products app's attribute definitions), and hides internal/media
258
+ // keys. Cached per tenant like the category tree.
259
+ // ---------------------------------------------------------------------------
260
+
261
+ interface LiveAttributeRow {
262
+ id: string;
263
+ code: string;
264
+ type: string;
265
+ group_id?: string | null;
266
+ position?: number;
267
+ labels?: Record<string, string> | null;
268
+ config?: { unit?: string } | null;
269
+ is_filterable?: boolean;
270
+ }
271
+ interface LiveAttributeGroupRow { id: string; code: string }
272
+ interface LiveAttributeOptionRow { attribute_id: string; code: string; labels?: Record<string, string> | null }
273
+
274
+ export interface LiveAttributeMeta {
275
+ type: string;
276
+ labels: Record<string, string> | null;
277
+ groupCode: string | null;
278
+ unit: string | null;
279
+ hidden: boolean;
280
+ position: number;
281
+ options: Record<string, Record<string, string>>;
282
+ isFilterable: boolean;
283
+ }
284
+
285
+ const ATTR_META_TTL_MS = 5 * 60 * 1000;
286
+ const attrMetaCache = new Map<string, { meta: Record<string, LiveAttributeMeta>; loadedAt: number }>();
287
+
288
+ /** Specs ordered by attribute group, then declared position. */
289
+ const SPEC_GROUP_RANK: Record<string, number> = { general: 0, technical: 1 };
290
+
291
+ async function listAllProducts<T>(path: string): Promise<T[]> {
292
+ const sdk = useRevenexxSdk();
293
+ const out: T[] = [];
294
+ let offset = 0;
295
+ for (let page = 0; page < 25; page++) {
296
+ const res = await sdk.call<{ items?: T[]; page?: { hasMore?: boolean } }>(
297
+ "GET", path, { query: { limit: 200, offset } },
298
+ );
299
+ const items = res.items ?? [];
300
+ out.push(...items);
301
+ if (items.length === 0 || !res.page?.hasMore) break;
302
+ offset += items.length;
303
+ }
304
+ return out;
305
+ }
306
+
307
+ export async function loadLiveAttributeMeta(): Promise<Record<string, LiveAttributeMeta>> {
308
+ const tenantKey = revenexxTenantKey();
309
+ const cached = attrMetaCache.get(tenantKey);
310
+ if (cached && Date.now() - cached.loadedAt < ATTR_META_TTL_MS) {
311
+ return cached.meta;
312
+ }
313
+
314
+ const [groups, attrs, options] = await Promise.all([
315
+ listAllProducts<LiveAttributeGroupRow>("/v1/products/attribute_groups"),
316
+ listAllProducts<LiveAttributeRow>("/v1/products/attributes"),
317
+ listAllProducts<LiveAttributeOptionRow>("/v1/products/attribute_options"),
318
+ ]);
319
+
320
+ const groupCodeById = new Map(groups.map(g => [g.id, g.code]));
321
+ const optionsByAttr = new Map<string, Record<string, Record<string, string>>>();
322
+ for (const o of options) {
323
+ const bucket = optionsByAttr.get(o.attribute_id) ?? {};
324
+ bucket[o.code] = o.labels ?? {};
325
+ optionsByAttr.set(o.attribute_id, bucket);
326
+ }
327
+
328
+ const meta: Record<string, LiveAttributeMeta> = {};
329
+ for (const a of attrs) {
330
+ const groupCode = a.group_id ? groupCodeById.get(a.group_id) ?? null : null;
331
+ meta[a.code] = {
332
+ type: a.type,
333
+ labels: a.labels ?? null,
334
+ groupCode,
335
+ unit: typeof a.config?.unit === "string" ? a.config.unit : null,
336
+ // Media-group attributes (image, …) are internal — never a spec row.
337
+ hidden: groupCode === "media" || a.code === "image",
338
+ position: typeof a.position === "number" ? a.position : 999,
339
+ options: optionsByAttr.get(a.id) ?? {},
340
+ isFilterable: a.is_filterable === true,
341
+ };
342
+ }
343
+
344
+ attrMetaCache.set(tenantKey, { meta, loadedAt: Date.now() });
345
+ return meta;
346
+ }
347
+
348
+ function prettifyAttrKey(key: string): string {
349
+ return key.replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase());
350
+ }
351
+
352
+ /**
353
+ * Build the product detail specification rows from the doc's `attrs`:
354
+ * localized label, option/unit-aware value, internal keys hidden. Degrades to
355
+ * prettified keys if the attribute metadata can't be loaded.
356
+ */
357
+ async function buildSpecRows(attrs: Record<string, unknown>, locale: Locale): Promise<{ id: number; name: string; value: string }[]> {
358
+ let meta: Record<string, LiveAttributeMeta> = {};
359
+ try {
360
+ meta = await loadLiveAttributeMeta();
361
+ }
362
+ catch {
363
+ meta = {};
364
+ }
365
+
366
+ const pick = (labels: Record<string, string> | null | undefined, fallback: string): string =>
367
+ labels?.[locale] ?? labels?.de ?? labels?.en ?? fallback;
368
+
369
+ const rows = Object.entries(attrs)
370
+ .filter(([key, value]) => {
371
+ if (value === null || value === undefined || value === "") return false;
372
+ if (key === "image") return false;
373
+ return !meta[key]?.hidden;
374
+ })
375
+ .map(([key, value]) => {
376
+ const m = meta[key];
377
+ const raw = String(value);
378
+ let display = m?.options?.[raw] ? pick(m.options[raw], raw) : raw;
379
+ if (m?.unit && !raw.includes(m.unit)) display = `${display} ${m.unit}`;
380
+ const rank = m?.groupCode && SPEC_GROUP_RANK[m.groupCode] !== undefined ? SPEC_GROUP_RANK[m.groupCode] : 5;
381
+ return { label: pick(m?.labels, prettifyAttrKey(key)), value: display, sort: rank * 1000 + (m?.position ?? 999) };
382
+ })
383
+ .sort((a, b) => a.sort - b.sort || a.label.localeCompare(b.label));
384
+
385
+ return rows.map((r, i) => ({ id: i + 1, name: r.label, value: r.value }));
386
+ }
@@ -58,7 +58,11 @@ async function actor(event: H3Event): Promise<{ contactId: string; name: string;
58
58
 
59
59
  function toCoverPosition(item: AppItem): OrderListPosition {
60
60
  return {
61
- id: String(item.id),
61
+ // cover treats position.id as the PRODUCT id (membership flag on the
62
+ // PDP, cart line identity) — map it from product_id, not the item row
63
+ // id. Legacy items written before product_id was persisted fall back to
64
+ // the row id so they still render (they just won't match a PDP product).
65
+ id: item.product_id ?? String(item.id),
62
66
  sku: item.sku ?? "",
63
67
  name: item.name,
64
68
  ...(item.image ? { image: item.image } : {}),
@@ -86,6 +90,9 @@ function toItemInput(position: OrderListPosition): Models.OrderListItemInput {
86
90
  const item: Record<string, unknown> = {
87
91
  name: position.name,
88
92
  quantity: Number(position.quantity) || 1,
93
+ // position.id is the cover product id — persist it as product_id so the
94
+ // PDP "on these lists" flag and cart de-dup can match by product later.
95
+ ...(position.id ? { product_id: position.id } : {}),
89
96
  ...(position.sku ? { sku: position.sku } : {}),
90
97
  ...(position.image ? { image: position.image } : {}),
91
98
  ...(position.unit ? { unit: position.unit } : {}),
@@ -100,6 +107,32 @@ function toItemInput(position: OrderListPosition): Models.OrderListItemInput {
100
107
  return item as Models.OrderListItemInput;
101
108
  }
102
109
 
110
+ /**
111
+ * cover position → the FLAT, camelCase params of `orderlistsItemsCreate`
112
+ * (single-item append). Distinct from `toItemInput`: that builds the
113
+ * snake_case `OrderListItemInput` wire model for the `items[]` arrays of
114
+ * create/replace, but `orderlistsItemsCreate` is a flat camelCase-param method
115
+ * — spreading the snake_case shape there silently dropped product_id/tax_rate/
116
+ * the *_slug fields (the SDK only reads its declared camelCase params).
117
+ */
118
+ function toItemCreateParams(position: OrderListPosition): Record<string, unknown> {
119
+ return {
120
+ name: position.name,
121
+ quantity: Number(position.quantity) || 1,
122
+ ...(position.id ? { productId: position.id } : {}),
123
+ ...(position.sku ? { sku: position.sku } : {}),
124
+ ...(position.image ? { image: position.image } : {}),
125
+ ...(position.unit ? { unit: position.unit } : {}),
126
+ ...(position.price != null ? { price: Number(position.price) } : {}),
127
+ ...(position.taxRate != null ? { taxRate: Number(position.taxRate) } : {}),
128
+ ...(position.costCenterId ? { costCenterId: position.costCenterId } : {}),
129
+ ...(position.positionTexts ? { positionTexts: position.positionTexts } : {}),
130
+ ...(position.customSku ? { customSku: position.customSku } : {}),
131
+ ...(position.categorySlug ? { categorySlug: position.categorySlug } : {}),
132
+ ...(position.subcategorySlug ? { subcategorySlug: position.subcategorySlug } : {}),
133
+ };
134
+ }
135
+
103
136
  function toCoverList(row: AppList): OrderList {
104
137
  return {
105
138
  id: row.id,
@@ -170,7 +203,7 @@ export async function updateOrderList(
170
203
  await sdk.orderlists.orderlistsItemsReplace({ listId: id, items: body.positions.map(toItemInput) });
171
204
  }
172
205
  for (const position of body.appendPositions ?? []) {
173
- await sdk.orderlists.orderlistsItemsCreate({ listId: id, ...toItemInput(position) });
206
+ await sdk.orderlists.orderlistsItemsCreate({ listId: id, ...toItemCreateParams(position) } as Parameters<typeof sdk.orderlists.orderlistsItemsCreate>[0]);
174
207
  }
175
208
 
176
209
  return toCoverList(await sdk.orderlists.orderlistsGet({ id }) as unknown as AppList);
@@ -0,0 +1,21 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ /** Cookie the storefront's locale selector persists the chosen market in. */
4
+ export const MARKET_COOKIE_NAME = "cover-market";
5
+
6
+ /**
7
+ * The buyer's active market for server-side scoping. Read from the cookie the
8
+ * locale selector sets — the BFF forwards it as X-Revenexx-Market
9
+ * (client.setMarket), so the gateway's Entity Scoping Engine filters
10
+ * market-scoped data to that market plus global (unassigned) rows. Undefined →
11
+ * no header → the API returns only global rows, so the shop works before any
12
+ * market is chosen. Market slugs are lowercase (e.g. "de").
13
+ */
14
+ export function resolveSelectedMarket(event: H3Event): string | undefined {
15
+ const raw = getCookie(event, MARKET_COOKIE_NAME);
16
+ if (!raw) {
17
+ return undefined;
18
+ }
19
+ const code = raw.trim().toLowerCase();
20
+ return /^[a-z][a-z0-9_]{0,62}$/.test(code) ? code : undefined;
21
+ }
@@ -118,6 +118,21 @@ function brokeredContext(): { tenant: string; jwt: string } | null {
118
118
  }
119
119
  }
120
120
 
121
+ /**
122
+ * The active market for the current request, from the `cover-market` cookie the
123
+ * locale selector sets. "" when none — then no X-Revenexx-Market is sent and the
124
+ * gateway returns only global rows. Per-request, so a market-bearing client is
125
+ * never reused as the process-wide singleton (see useRevenexxSdk).
126
+ */
127
+ function activeMarket(): string {
128
+ try {
129
+ return resolveSelectedMarket(useEvent()) ?? "";
130
+ }
131
+ catch {
132
+ return "";
133
+ }
134
+ }
135
+
121
136
  /**
122
137
  * The tenant slug the current request's SDK calls are scoped to — the cache
123
138
  * key for any server-side cache of gateway data (markets, categories, …).
@@ -135,7 +150,10 @@ export function revenexxTenantKey(): string {
135
150
 
136
151
  export function useRevenexxSdk(): RevenexxSdk {
137
152
  const brokered = brokeredContext();
138
- if (!brokered && sdk) {
153
+ const market = activeMarket();
154
+ // The process-wide singleton must not carry a per-request market — only
155
+ // reuse it when there's no brokered context AND no active market.
156
+ if (!brokered && !market && sdk) {
139
157
  return sdk;
140
158
  }
141
159
 
@@ -156,6 +174,12 @@ export function useRevenexxSdk(): RevenexxSdk {
156
174
  const client = new Client()
157
175
  .setEndpoint(endpoint)
158
176
  .setTenant(tenant);
177
+ // Active market (scope filter) → X-Revenexx-Market. Only when set: an empty
178
+ // value would send an empty header instead of letting the API default to
179
+ // global rows.
180
+ if (market) {
181
+ client.setMarket(market);
182
+ }
159
183
  // Auth: the brokered context wins — it is a Zitadel JWT the gateway
160
184
  // verifies against the same JWKS as any interactive caller, so one theme
161
185
  // build serves any tenant without per-site credentials. The explicit
@@ -215,7 +239,7 @@ export function useRevenexxSdk(): RevenexxSdk {
215
239
  };
216
240
  // Brokered instances are request-scoped (the JWT rotates per invocation)
217
241
  // — only the env-credential client is a process-wide singleton.
218
- if (!brokered) {
242
+ if (!brokered && !market) {
219
243
  sdk = instance;
220
244
  }
221
245
  return instance;